简体   繁体   English

如果我更改页面,则tampermonkey脚本将停止工作

[英]tampermonkey script stops working if I change the page

I am using Tampermonkey to save time on frequent tasks. 我正在使用Tampermonkey来节省执行常见任务的时间。 The goal is to get content of an element on www.example1.com, navigate to another page, and do stuff there. 目的是在www.example1.com上获取元素的内容,导航到另一个页面,然后在其中进行填充。 The starting page is www.example1.com as seen from match . match看到,起始页面是www.example1.com。 This is the code I am using: 这是我正在使用的代码:

//@match  http://example1.com

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

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

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

None of the code after changing URLs ever gets executed. 更改URL后,没有代码会执行。 Why, and what is the workaround? 为什么,解决方法是什么?

Allow the userscript on both urls and use GM_setValue / GM_getValue to organize the communication. 在两个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
    }
}
  • This is a simplified example. 这是一个简化的示例。 In the real code you may want to use location.host or location.origin or match location.href with regexp depending on what the real urls are. 在实际代码中,您可能要使用location.hostlocation.origin或将location.href与regexp匹配,具体取决于实际的URL。
  • To pass complex objects serialize them: 要传递复杂的对象,请将它们序列化:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM