描述

该函数主要用于实现跨域传输信息调用,如从 www.example.com 请求 upload.example.com 的内容。

语法

请求方式,最常见的有 GET 与 POST 两种。

也有其它的请求方式,详细请翻阅 w3 标准。 请求访问的地址。 默认为 false。当为 true 的时候将使用 .sendAsBinary() 方法。 任意对象。搞对象同时将为 Response 对象的 context。 提交给网页的数据,一般为 POST 操作。 提交给网页使用的 HTTP 头部数据。 提交给网站的用户名 提交给网站的密码 (详细: 基础用户验证)。 当该值为 true 时,请求结束前将导致浏览器界面无项应。该模式下返回值即为返回数据。 超过指定数字的毫秒数后强行结束网页请求。 包含了 onabort、onerror、onload、onprogress 这四个上传回调函数的对象。 用于指定请求页面的元数据,如 text/html; charset=GBK


  • 回调参数
  • 回调参数将会被传入一个参数,请参考下方的「请求对象」。

可用的回调参数:

  • onabort 断开操作时的回调
  • onerror 请求出错时的回调
  • onload 请求完毕后时的回调
  • onprogress 请求进度更换时的回调
  • onreadystatechange 准备状态切换时的回调
  • ontimeout 请求超时时的回调

请求对象

所有的回调参数调用时都会传入一个变量。根据回调的不同,下述数据可能不全部可用。

  • readyState 准备状态
  • responseHeaders 请求页面的头部信息
  • responseText 请求的页面内容
  • status 请求页面的状态,如 404
  • statusText 请求页面的内容,如 404 Not Found

其中,GM 还引用了自己独有的属性值:

使用 API 时传入的 context 属性。 获取跳转后的链接地址。

而针对 progress 的进度回调,传参包含下述属性:

  • lengthComputable
  • loaded
  • total

返回

在默认(异步请求, asynchronous)请求方式下,将返回一个带有 abort() 方法的对象。

在同步请求方式下,将返回一个带有 abort() 及下述属性的对象:

  • finalUrl
  • readyState
  • responseHeaders
  • responseText
  • status
  • statusText

例子

最基础的调用

  1. GM_xmlhttpRequest({
  2. method: "GET",
  3. url: "http://www.example.com/",
  4. onload: function(response) {
  5. alert(response.responseText);
  6. }
  7. });

GET 调用

  1. GM_xmlhttpRequest({
  2. method: "GET",
  3. url: "http://www.example.net/",
  4. headers: {
  5. "User-Agent": "Mozilla/5.0", // 如果未指定则使用浏览器默认值.
  6. "Accept": "text/xml" // 如果未指定则教给浏览器自行判断
  7. },
  8. onload: function(response) {
  9. var responseXML = null;
  10. // 插入 responseXML 到现有对象 (仅限于 XML 对象)
  11. if (!response.responseXML) {
  12. responseXML = new DOMParser()
  13. .parseFromString(response.responseText, "text/xml");
  14. }
  15.  
  16. GM_log([
  17. response.status,
  18. response.statusText,
  19. response.readyState,
  20. response.responseHeaders,
  21. response.responseText,
  22. response.finalUrl,
  23. responseXML
  24. ].join("\n"));
  25. }
  26. });

POST 请求

当发出 POST 请求时,大多数网站都要求 Content-Type 头部设定为 application/x-www-form-urlencoded 才允许提交。

  1. GM_xmlhttpRequest({
  2. method: "POST",
  3. url: "http://www.example.net/login",
  4. data: "username=johndoe&password=xyz123",
  5. headers: {
  6. "Content-Type": "application/x-www-form-urlencoded"
  7. },
  8. onload: function(response) {
  9. if (response.responseText.indexOf("Logged in as") > -1) {
  10. location.href = "http://www.example.net/dashboard";
  11. }
  12. }
  13. });

HEAD 请求

如同 HTTP 的定义,你可以发出一个 HEAD 请求只获取网页的头部信息。

  1. GM_xmlhttpRequest({
  2. url: "http://www.example.com",
  3. method: "HEAD",
  4. onload: function(response) {
  5. GM_log(response.responseHeaders);
  6. }
  7. });