如果我更改页面,tampermonkey 脚本将停止工作
tampermonkey script stops working if I change the page
我正在使用 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);
None 更改 URL 后的代码会被执行。为什么,解决方法是什么?
允许两个 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.host
或 location.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) }
我正在使用 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);
None 更改 URL 后的代码会被执行。为什么,解决方法是什么?
允许两个 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.host
或location.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) }