油猴腳本實現跨域請求或下載文件 tampermonkey


油猴腳本實現跨域請求或下載文件

標簽(空格分隔): 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 和一些自己的總結


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM