Access-Control-Allow-Origin不允许获取 – > Origin *
我正在制作一个非常简单的Chrome扩展程序,将http协议上的页面重定向到https协议(如果存在)。 我正在调试,我找到了facebook,http和https都有。
代码在这里:
function redirect() { chrome.tabs.query({active: true}, function(tabArray) { var currentURL = tabArray[0].url; //http://facebook.com var httpsURL = generateSSL(currentURL); //https://facebook.com if(httpsURL == currentURL){ console.log(currentURL+" is already on HTTPS"); chrome.browserAction.setIcon({path:"../images/padlock_green.png"}); } else if(checkSSL(httpsURL)){ chrome.tabs.update(tabArray[0].id, {url: httpsURL}); chrome.browserAction.setIcon({path:"../images/padlock_green.png"}); chrome.browserAction.setBadgeText({text:"SSL"}); console.log("SSL found,"+currentURL+" redirected to"+httpsURL); } else { //donothing console.log(currentURL+" has no SSL"); chrome.browserAction.setIcon({path:"../images/padlock_red.png"}); } }); }
ajax电话:
function checkSSL(url){ $.support.ajax = true; $.ajax({ url: url, type:'HEAD', error: function() { return false; }, success: function() { return true; } }); }
问题是,我在控制台中遇到以下错误信息:
XMLHttpRequest cannot load https://www.facebook.com/. Origin chrome-extension://pgidanbjmliilmmohlphbagcapafjjpg is not allowed by Access-Control-Allow-Origin.
我没有任何想法可能是什么问题:(
您的代码有几个小问题:
-
您的清单文件仅请求
http://*/*
, 而不是https://*/*
权限,因此您对HTTPS站点的请求失败。 您需要具有*://*/*
的权限,因此您可以通过所有协议获取所有域上的所有页面,而不仅仅是通过HTTP。 -
第二个问题是你希望你的
$.ajax
调用返回一个布尔值,但事实并非如此。$.ajax
调用有两个回调 ,每个回调都返回一个布尔值,但checkSSL
在Ajax调用完成之前终止,这意味着checkSSL
总是返回undefined
。
你要做的是为checkSSL
提供一个回调函数作为参数:
function checkSSL(url, callback){ $.ajax({ url: url, type:'HEAD', error: function() { callback(false); }, success: function() { callback(true); } }); }
然后,使用该回调在调用checkSSL
之后运行调用代码:
function redirect() { chrome.tabs.query({active: true}, function(tabArray) { var currentURL = tabArray[0].url; //http://facebook.com var httpsURL = generateSSL(currentURL); //https://facebook.com if(httpsURL == currentURL){ console.log(currentURL+" is already on HTTPS"); chrome.browserAction.setIcon({path:"../images/padlock_green.png"}); } else { // call checkSSL and take action in an anonymous callback function! checkSSL(httpsURL, function(urlDoesExist) { if(urlDoesExist) { chrome.tabs.update(tabArray[0].id, {url: httpsURL}); chrome.browserAction.setIcon({path:"../images/padlock_green.png"}); chrome.browserAction.setBadgeText({text:"SSL"}); console.log("SSL found,"+currentURL+" redirected to"+httpsURL); } else { //donothing console.log(currentURL+" has no SSL"); chrome.browserAction.setIcon({path:"../images/padlock_red.png"}); } }); } }); }
请注意第一个以下代码的更改。 在Ajax调用解决之前我们无法决定要做什么,因此我们有Ajax success
和error
函数使用布尔参数触发回调。 然后,该回调函数根据布尔值的值执行操作。
如果您打包扩展程序,则可以执行跨域请求,但如果您将其创建为托管应用程序/扩展程序,则请参阅:请参阅:
Chrome扩展跨域请求