油猴脚本实现跨域请求或下载文件 tampermonkey

时间:2024-02-18 21:23:47

油猴脚本实现跨域请求或下载文件

标签(空格分隔): js tampermonkey 油猴


1.介绍

在以往的XmlHttprequest对象中想要跨域请求基本上就是靠jsonp,油猴脚本可以实现自定义网页脚本,但是他同样无法避免的要被CORS阻止。这篇文章就是讲解如何使用@grant注解实现使用油猴自带的GM_xmlhttpRequest发送跨域请求。

2.什么是油猴脚本

油猴脚本是一个浏览器插件通常在google中叫tampermonkey,在火狐中叫greasemonkey。具体的用法可以去百度一下。这里提供两个现在可以使用的脚本网站
http://userscripts-mirror.org/
https://greasyfork.org/zh-CN/scripts

3.什么是跨域请求

通俗的来说就是在一个网页去请求了别的网页(这些网页不属于这个网站或者端口协议不同)。

主要原因还是由于安全限制(同源策略, 即JavaScript或Cookie只能访问同域下的内容)
http://blog.csdn.net/hfahe/article/details/7730944

4.如何在脚本中使用GM_xmlhttpRequest
在很久以前的中国有一个石猴子(偏题)。通常新建一个脚本之后是这样的。

// ==UserScript==
// @name         New Userscript
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        url
// @grant        none
// ==/UserScript==
/* jshint -W097 */
\'use strict\';

// Your code here...

其他的@..不说,只看@grant在官方文档中是这样描述的:

@grant is used to whitelist GM_* functions, the unsafeWindow object and some powerful window functions. If no @grant tag is given TM guesses the scripts needs.

就是说使用@grant可以使用一些加强函数这些函数都是以GM_开头的。

If @grant is followed by \'none\' the sandbox is disabled and the script will run directly at the page context. In this mode no GM_* function but the GM_info property will be available.

如果@grant是none的话就只能使用GM_info这个函数了。
老偏题呢。

这是我们要引用

// @grant GM_xmlhttpRequest

之后我们的代码中就可以使用GM_xmlhttpRequest函数了
// ==UserScript==
// @name         New Userscript
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://www.zybuluo.com/mdeditor
// @grant        GM_xmlhttpRequest
// @grant        GM_download
// ==/UserScript==
/* jshint -W097 */
\'use strict\';
GM_xmlhttpRequest({
  method: "GET",
  url: "http://www.qq.com/",
  onload: function(response) {
     //这里写处理函数
  }
});

处理这些属性之外还有一些其他的属性:

  • url - the URL from where the data should be downloaded
  • name - thefilename - for security reasons the file extension needs to bewhitelisted at the Tampermonkey options page
  • headers - seeGM_xmlhttpRequest for more details saveAs - boolean value, show asaveAs dialog
  • onload - function() {} - callback function that iscalled when the download has finished
  • onerror - function(download) {}
  • callback function that is called when there was an error

以上内容来自https://tampermonkey.net/documentation.php 和一些自己的总结