[英]Getting -> Origin * is not allowed by Access-Control-Allow-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"});
}
});
}
});
}
注意第一個else
下面的代碼更改。 在Ajax調用解決之前,我們無法決定要做什么,因此,我們擁有Ajax success
和error
函數會觸發帶有布爾參數的回調。 然后,該回調函數根據布爾值執行操作。
如果打包擴展程序,則允許跨域請求,但如果將其創建為托管應用程序/擴展程序則不允許,請參閱:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.