如果我更改页面,tampermonkey脚本停止工作 [英] tampermonkey script stops working if I change the page
问题描述
我使用Tampermonkey为频繁的任务节省时间。我们的目标是在www.example1.com上获取元素的内容,导航到另一个页面,并在那里完成任务。从 match
可以看到起始页面是www.example1.com。这是我使用的代码:
I am using Tampermonkey to save time on frequent tasks. The goal is to get content of an element on www.example1.com, navigate to another page, and do stuff there. The starting page is www.example1.com as seen from match
. 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);
更改URL后的任何代码都不会被执行。为什么和什么是解决方法?
None of the code after changing URLs ever gets executed. Why, and what is the workaround?
推荐答案
在这两个URL上允许userscript并使用 GM_setValue
/ GM_getValue
来组织沟通。
Allow the userscript on both urls and use GM_setValue
/GM_getValue
to organize the communication.
//@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.host
或location.origin
或匹配
传递复杂对象对它们进行序列化:
- This is a simplified example. In the real code you may want to use
location.host
orlocation.origin
or matchlocation.href
with regexp depending on what the real urls are. 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) }
这篇关于如果我更改页面,tampermonkey脚本停止工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!