我一直在尝试在 chrome 扩展中使用一些 ajax。
我有一个内容脚本,应该向现有页面添加一些 html。
我尝试过 JQuery.get
、JQuery.load
和 ng-include
。
并且所有这些都在控制台中显示警告,告诉我同步 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']);
最佳答案
好的,发生的事情是这样的:
1 - 扩展域与页面域不同,因此它尝试从页面域而不是扩展文件加载内容。 (并且找不到资源)。在这种情况下,警告消息完全具有误导性。
解决方案:使用chrome.extention.getURL('myhtml.html')
获取正确的完整网址。或者使用扩展程序的 ID 连接字符串以创建完整路径。
var txt = '<div id="myNewDiv" ng-controller="myController">{{testing}}<div ng-include="' + "'" + chrome.extension.getURL('myhtml.html') + "'" + '"></div></div>';
2 - 即使这样做,也存在跨域请求问题。该页面仅接受来自其自己域的请求,除非您授予其正确的权限。需要在 manifest.json
文件中添加对此资源的权限:
{
"manifest_version": 2,
..... among many others ....
"web_accessible_resources": [
"myhtml.html"
]
}
关于jquery - 为什么我的 ajax 调用在 Chrome 扩展中是同步的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31062873/