Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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);

None of the code after changing URLs ever gets executed. Why, and what is the workaround?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
782 views
Welcome To Ask or Share your Answers For Others

1 Answer

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() + '
' + 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('
')[0] < 10*1000) {
        ID = ID.split('
')[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) }
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...