使用 XMLHttpRequest 为 Safari 扩展进行编码
在我的扩展中,我将访问级别创建为“全部”,并为每个域添加白名单为 http://*/*
。
我的 JS 文件中有以下代码(作为结束脚本运行):
var feedbackmsg = "message goes here";
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', 'http://mysitename.com/feedback.php', true);
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("html=" + feedbackmsg);
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
alert(xmlhttp.getAllResponseHeaders());
if (xmlhttp.status == 200) {
alert("send");
} else {
alert("error");
}
}
}
每当我运行它时,我在警报框中都没有收到任何标头响应以及错误警报消息。我该如何解决这个问题?
In my extension, I create Access Level as "All" as well as I add whitelists as http://*/*
too for every domain.
And I have following code in my JS file (which run as end script):
var feedbackmsg = "message goes here";
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', 'http://mysitename.com/feedback.php', true);
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("html=" + feedbackmsg);
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
alert(xmlhttp.getAllResponseHeaders());
if (xmlhttp.status == 200) {
alert("send");
} else {
alert("error");
}
}
}
Whenever I run it, I am getting no header respond in alert box as well as error alert message. How can I resolve the problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为,无论它是否是扩展,XMLHttpRequest(如果注入到页面中)都不允许访问页面当前域之外的任何内容。控制台只是说请求已取消。至少,我刚才测试的时候是这样的。 (当我测试时,白名单或黑名单中没有任何网址,但访问选项设置为“全部”。)
您可以尝试使用 XHR 对象转到与要“调用”的域相同的域在你的代码中,看看它是否成功。如果是这样,您就会知道这是因为页面的域和 XHR 请求必须匹配。
但是,您似乎可以从扩展程序的全局页面执行跨站点 ajax 请求(很奇怪)。至少现在看来它对我有用。这实际上有点可怕(我希望从扩展调用随机服务器更困难),但它有效。
不过不知道这是否对你有帮助。
Whether or not it's an extension, XMLHttpRequest (if injected into a page) isn't allowed to access anything outside the page's current domain, I think. The console just says that the request was cancelled. At least, that was the case for me when I tested it just now. (I didn't have any urls in the whitelist or blacklist when I tested, but the Access option was set to "all".)
You can try going to the same domain as the one you want to "call" with the XHR object in your code, and see if it succeeds then. If it does, you'll know it's because the domain of the page and the XHR request must match.
However, it appears you can do cross-site ajax request from the extension's global page (oddly enough). At least it seemed to work for me just now. That's actually a little scary (I'd prefer it to be more difficult to call up a random server from an extension) but it worked.
Don't know if that helps you out, though.