【问题标题】:tampermonkey script stops working if I change the page如果我更改页面,tampermonkey 脚本将停止工作
【发布时间】:2016-02-04 02:00:04
【问题描述】:

我正在使用 Tampermonkey 来节省执行频繁任务的时间。目标是在 www.example1.com 上获取元素的内容,导航到另一个页面,然后在那里做一些事情。从match 看到的起始页是 www.example1.com。这是我正在使用的代码:

//@match  http://example1.com

var item = document.getElementById("myId").textContent;

window.open("http://example2.com","_self");

setTimeOut(function(
//perform clicks on this page
){},3000);

更改 URL 后的任何代码都不会被执行。为什么,解决方法是什么?

【问题讨论】:

    标签: javascript html greasemonkey tampermonkey


    【解决方案1】:

    允许两个 url 上的用户脚本,并使用 GM_setValue/GM_getValue 来组织通信。

    //@match   http://example1.com
    //@match   http://example2.com
    //@grant   GM_getValue
    //@grant   GM_setValue
    
    if (location.href.indexOf('http://example1.com') == 0) {
        GM_setValue('id', Date.now() + '\n' + document.getElementById("myId").textContent);
        window.open("http://example2.com","_self");
    } else if (location.href.indexOf('http://example2.com') == 0) {
        var ID = GM_getValue('id', '');
        if (ID && Date.now() - ID.split('\n')[0] < 10*1000) {
            ID = ID.split('\n')[1];
            .............. use the ID
        }
    }
    
    • 这是一个简化的示例。在实际代码中,您可能希望使用location.hostlocation.origin 或将location.href 与正则表达式匹配,具体取决于实际网址。
    • 传递复杂对象序列化它们:

      GM_setValue('test', JSON.stringify({a:1, b:2, c:"test"}));
      

      try { var obj = JSON.parse(GM_getValue('test')); }
      catch(e) { console.error(e) }
      

    【讨论】:

    • 简洁的方法。我实现了它,但出现错误:未定义 GM_setValue。
    • 您很可能忘记在@require 中声明它,如答案所示。
    • 你的读心能力:我确实忘记声明了。我添加了声明,但仍然收到错误消息。声明的顺序是否相关?
    • 不是@require@grant。编辑答案。
    猜你喜欢
    • 2021-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多