V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
tt210
V2EX  ›  问与答

Tampermonkey 的 GM_xmlhttpRequest 如何在 onload 回调函数中访问到传入的 url。

  •  
  •   tt210 · Oct 14, 2015 · 3961 views
    This topic created in 3849 days ago, the information mentioned may be changed or developed.

    Tampermonkey 的 GM_xmlhttpRequest 貌似不支持同步访问,只支持异步返回,于是当在循环中的时候,传入的 url 无法访问到,只能访问到最后传入的 url 。求解决方法。 demo 如下:

    // ==UserScript==
    // @name         Decode BaiDu Link
    // @namespace    http://your.homepage/
    // @version      0.1
    // @description  Decode baidu Link
    // @author       my
    // @match        https://www.baidu.com/s*
    // @grant        GM_xmlhttpRequest
    // @grant        GM_setClipboard
    // @require      http://www.w3school.com.cn/jquery/jquery.js
    // ==/UserScript==
    $(document).ready(function () {
        var sUrl = $('.t a'),
            QueryUrl;
        sUrl.map(function () {
            QueryUrl = $(this).attr('href');
            //alert(QueryUrl);
            GM_xmlhttpRequest({
                method: 'GET',
                url: QueryUrl,
                synchronous: true,
                headers: {
                    'User-agent': 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)',
                    'Accept': 'text/html, application/xhtml+xml, */*',
                },
                onload: function(data) {
                    alert(QueryUrl + '\n' + data.finalUrl);
    
                    sUrl.map(function () {
                        if ($(this).attr('href') == QueryUrl) {
                            $(this).attr('href', data.finalUrl);
                        }
                    });
                },
                onerror:function () {
                    alert("error");
                }
            });
        });
    });
    
    tt210
        1
    tt210  
    OP
       Oct 15, 2015
    找到方法了,传入参数时加 context ,里面放入想传入的东西即可。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5978 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 41ms · UTC 02:19 · PVG 10:19 · LAX 19:19 · JFK 22:19
    ♥ Do have faith in what you're doing.