How to Use Tampermonkey to reload another tab?

前端 未结 1 1449
说谎
说谎 2020-12-11 09:23

I want to refresh a certain tab when the current tab changes, using Tampermonkey.

I am a user of Duolingo, but I am not happy with their new change of

相关标签:
1条回答
  • 2020-12-11 09:47

    You can do this by:

    1. Set your Tampermonkey script to run on both domains.
    2. Communicate between script instances using GM_setValue()Doc and GM_addValueChangeListener()Doc and, optionally, GM_getValue()Doc.

    Say, for example, that you wanted to monitor this random question, and reload its timeline page every time you clicked a vote button or the favorite star.

    This complete working Tampermonkey script does that:

    // ==UserScript==
    // @name     _Cross tab, cross domain script communication
    // @match    *://stackoverflow.com/questions/521295/*
    // @match    *://stackoverflow.com/posts/521295/timeline
    // @require  https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
    // @grant    GM_setValue
    // @grant    GM_addValueChangeListener
    // ==/UserScript==
    
    const xmssionKey = "Last vote-button click event";
    
    //-- Are we on the "interactive" page/site/domain or the "monitoring" one?
    if (location.pathname.includes ("questions") ) {
        //-- On the "interactive page/tab...
        //-- Hook into the page's vote and favorite buttons:
        $(".inner-content").on ("click", ".vote a", zEvent => {
            var tmStamp   = new Date ().getTime ();
            var ctMessage = `Button ${zEvent.target.className} clicked - ${tmStamp}`;
            console.log (ctMessage);
    
            //-- Send message to monitoring tab.
            GM_setValue (xmssionKey, ctMessage);
        } );
    }
    else {
        //-- On the "monitoring" page/tab...
        //-- Listen for new message:
        GM_addValueChangeListener (
            xmssionKey, (keyName, oldValue, newValue, bRmtTrggrd) => {
                console.log (`Received new event: ${newValue}`);
                //-- User feedback, esp useful with time delay:
                document.title = "Reloading...";
                /*-- Important:
                    May need to wait 1 to 300 seconds to allow for
                    web-app / database / API delays and/or caching.
                    1222 == 1.2 seconds
                */
                setTimeout ( () => {location.reload(); }, 1222);
        } );
    }
    
    1. Install the script.
    2. Open the timeline page.
    3. Open the question page.
    4. Click on one of the vote buttons or on the favorite star.
    5. You will see the timeline page reload automatically.

    Note that for this particular example, both pages are on the same domain (Merely to make it easier for everyone to run the demo script), but the code/strategy works just as well for cross-domain pages.

    0 讨论(0)
提交回复
热议问题