我解析一个网页,根据内容,我需要对我的localhost进行ajax调用。 在本地主机上将是一个PHP脚本,它将通过AJAX交换数据,可能是JSON格式(我还不确定,仍在阅读和测试)。
这是一个插件,我尝试在Google页面上进行测试
我遵循这个简单的ajax示例:
https://www.w3schools.com/xml/ajax_xmlhttprequest_response.asp
我成功地打了电话
//loadDoc("http://localhost/index.php", myCallback); <-- this NOT
//loadDoc("https://www.google.de", myCallback); <-- this WORKS
/*
Content Security Policy: Ignoring “'unsafe-inline'” within script-src: ‘strict-dynamic’ specified (unknown)
Content Security Policy: Ignoring “https:” within script-src: ‘strict-dynamic’ specified (unknown)
Content Security Policy: Ignoring “http:” within script-src: ‘strict-dynamic’ specified
*/
function loadDoc(url, cFunction) {
var xhttp;
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
cFunction(this);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
function myCallback(xhttp) {
alert("I'm alive from my local server");
}
(BIG)问题是我发现“内容安全策略”不允许我调用其他域,即使我在我自己的上下文中(我的浏览器,FF 53)。
现在看来,至少对于我需要的GET请求,这很容易被欺骗,方法是在DOM中插入一个脚本,就像这样
尤其是Rob W的这篇伟大帖子
Insert code into the page context using a content script
所以我尝试了这样,但仍然无法正常工作。
// var actualCode = ['/* Code here. Example: */' + 'alert(0);',
// '// Beware! This array have to be joined',
// '// using a newline. Otherwise, missing semicolons',
// '// or single-line comments (//) will mess up your',
// '// code ----->'].join('\n');
var script = document.createElement('script');
script.src = "http://localhost/index.php";
script.type = "text/javascript";
document.appendChild(script);
// script.textContent = actualCode;
// (document.head||document.documentElement).appendChild(script);
// script.remove();
安全性不是问题,因为我只使用我的localhost。 我想念的是什么?
EDITED
这些是Firefox调试器显示的错误
Blocked loading mixed active content “http://localhost/index.php”[Learn More] axtest.js:16
Content Security Policy: Ignoring “'unsafe-inline'” within script-src: ‘strict-dynamic’ specified (unknown)
Content Security Policy: Ignoring “https:” within script-src: ‘strict-dynamic’ specified (unknown)
Content Security Policy: Ignoring “http:” within script-src: ‘strict-dynamic’ specified
答案 0 :(得分:1)
将其附加到body或head元素,而不是根document
:
document.body.appendChild(script);
混合活动内容错误是由于通过https(SSL)加载初始页面然后尝试加载http(不安全)URL。您可以在没有https的情况下加载页面,也可以在您正在呼叫的网址上设置https。
答案 1 :(得分:0)
尽管我已经接受了答案,但我找到了一个很容易解决的问题。 关于本地浏览器安全策略,不需要注入任何JS代码。
首先,插件的manifest.json必须使用此
进行更新 "permissions": [
"history",
"browsingData",
"tabs",
"<all_urls>",
"http://localhost/*",
"storage"
]
其次(感谢@Quentin)需要重新配置本地浏览器策略。通过禁用about:config菜单中的security.csp.enable
关闭整个浏览器的CSP