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

2015-10-14 23:47:46 +08:00
 tt210

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");
            }
        });
    });
});
3287 次点击
所在节点    问与答
1 条回复
tt210
2015-10-15 00:07:13 +08:00
找到方法了,传入参数时加 context ,里面放入想传入的东西即可。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/228121

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX