为什么我的ajax在Chrome扩展程序中调用同步?

Dan*_*ler 6 ajax jquery google-chrome-extension content-script angularjs

我一直试图在chrome扩展中使用一些ajax.

我有一个内容脚本,应该在现有页面中添加一些html.

我试过了JQuery.get,JQuery.load而且ng-include.

所有这些都在控制台中显示一个警告,告诉我synchronous XHR已被弃用(这些不是同步的???).然后页面显示这种奇怪的行为,告诉我有些Pusher未定义,然后刷新页面并杀死我插入的div.

可能有什么不对?

示例代码 - 如果我启用第一个var txt,它可以很好地工作.如果我启用了第二个var txt(已注释),则失败.

 //this first line works perfectly
 var txt = '<div id="myNewDiv" ng-controller="myController">{{testing}}</div>'; 

//this shows the warning and a really weird behavior
//var txt = '<div id="myNewDiv" ng-controller="myController">{{testing}}<div ng-include="' + "'myhtml.html'" + '"></div></div>'; 


$('#a-certain-div-in-the-page').after(txt)

var app = angular.module('myApp', [])
    .controller('myController', function($scope) {
        $scope.testing = 'Welcome!';
    });

angular.bootstrap(document, ['myApp']);
Run Code Online (Sandbox Code Playgroud)

Dan*_*ler 6

好的,这是发生的事情:

1 - 扩展域与页面域不同,因此它尝试从页面的域加载内容,而不是从扩展文件加载.(并没有找到资源).在这种情况下,警告信息完全是误导性的.

解决方案:用于chrome.extention.getURL('myhtml.html')获取正确的完整URL.或者使用扩展程序的ID连接字符串以创建完整路径.

 var txt = '<div id="myNewDiv" ng-controller="myController">{{testing}}<div ng-include="' + "'" + chrome.extension.getURL('myhtml.html') + "'" + '"></div></div>'; 
Run Code Online (Sandbox Code Playgroud)

2 - 即使这样做,也存在跨域请求问题.除非您为其提供正确的权限,否则该页面仅接受来自其自己域的请求.有必要在manifest.json文件中添加对此资源的权限:

{
    "manifest_version": 2,

    ..... among many others ....

    "web_accessible_resources": [
        "myhtml.html"
    ]

}
Run Code Online (Sandbox Code Playgroud)