gpt4 book ai didi

javascript - XMLHttpRequest.send() 在请求 DOM 对象时抛出异常

转载 作者:行者123 更新时间:2023-11-30 18:23:13 26 4
gpt4 key购买 nike

我想在 Firefox/Greasemonkey 用户脚本中检索一个 HTML 页面作为 document

编辑:这不是跨域请求。

这是我的示例代码:

var r = new XMLHttpRequest();
r.open("GET", document.location.href, true);
r.responseType = "document";
r.send(null);

这看起来就像 https://developer.mozilla.org/en/HTML_in_XMLHttpRequest 中的示例,但是 r.send(null) 会导致 TypeError。原因,而不是抛出!将行包装在 try...catch 中不会改变任何东西,它似乎是回调或事件处理程序引发了异常:

TypeError: document.location is null

回溯是指 Firefox 内部的 event.js 文件,而不是我的脚本。

删除设置 responseType 的行可以消除异常,添加回调则不会。但是,响应是有效的并且 responseXML 提供了一个 DOM 树。我正在使用 FF 13.0.1。

我是不是遗漏了什么或者这是一个错误?

解决方案:这与 Mozilla 的 Addon Builder 而不是 Firefox 创建的扩展有关。

最佳答案

脚本正在 google.com 上运行,您正在尝试获取 google.de,对吗?这是一个跨域请求。 (此外,问题代码不是 XMLHttpRequest 的有效同步或异步使用。)

要在 Greasemonkey 脚本(或 Chrome)中进行跨域(或不跨域)AJAX,请使用 GM_xmlhttpRequest() .
请注意,GM_xmlhttpRequest() 目前不允许您指定 responseType,但在这种情况下您不需要这样做。如果您想要一个经过良好解析的文档,请使用 DOMParser

综合起来:

GM_xmlhttpRequest ( {
method: 'GET',
//url: 'https://www.google.de/',
url: location.href, // self get, checking for updates
onload: function (respDetails) {
processResponse (respDetails);
}
} );

function processResponse (respDetails) {
// DO ALL RESPONSE PROCESSING HERE...
var parser = new DOMParser ();
var doc = parser.parseFromString (respDetails.responseText, "text/html");

//--- Example showing that the doc is fully parsed/functional...
console.log (doc.querySelectorAll ("p") );
}




PS:因为这毕竟不是跨域,所以原始代码,更正将是:

var r           = new XMLHttpRequest();

r.onload = function () {
// DO ALL RESPONSE PROCESSING HERE...
console.log (this.response.querySelectorAll ("div") );
}
r.open ("GET", location.href, true);
r.responseType = "document";
r.send (null);

用于异步请求。

关于javascript - XMLHttpRequest.send() 在请求 DOM 对象时抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11556139/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com