我解析一个网页,根据内容,我需要对本地主机进行 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");
}
(大)问题是我发现“内容安全策略”不允许我调用其他域,即使我在自己的上下文中(我的浏览器,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();
安全性不是问题,因为我只使用本地主机。 我想念这里什么?
已编辑
这些是 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
最佳答案
将其附加到正文或头元素,而不是根文档
:
document.body.appendChild(script);
混合事件内容错误是由于通过 https(SSL) 加载初始页面,然后尝试加载 http(不安全)URL 造成的。加载不带 https 的页面或在您调用的 URL 上设置 https。
关于Javascript、ajax、跨域调用、覆盖内容安全策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44304351/