tampermonkey script stops working if I change the page

巧了我就是萌 提交于 2019-11-29 16:14:50
wOxxOm

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
    }
}
  • 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.
  • 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) }
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!