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

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

javascript - How to run code after changing the URL via window.location?

I'm doing this but it doesn't work:

window.addEventListener("load", function load(event){
    alert('hola');
},false);

window.location.assign("about:blank");

It's a Greasemonkey script. The new location is loaded but the alert is never shown.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Once you change the window.location, the current instance of your Greasemonkey script is purged. To "run code" after the location change, you need to set the script to trigger on the new page (about:blank in this case), and then use a flag to signal that the new page was reached via this script redirecting the original page.

  1. Make sure that the script's @include or @match directives fire on the new page.
  2. Use GM_setValue() to set the flag letting the script know it has been deliberately reincarnated.

Here is a complete, working script that illustrates the process:

// ==UserScript==
// @name     _Fire after redirect to about:blank
// @include  about:blank
// @include  http://YOUR_SERVER.COM/YOUR_PATH/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @grant    GM_setValue
// @grant    GM_getValue
// @grant    GM_deleteValue
// ==/UserScript==

//-- Are we on a blank page after a redirect by this script?
var bAfterRedirect = GM_getValue ("YouHaveBeenRedirected", false);

//-- Always erase the stored flag.
GM_deleteValue ("YouHaveBeenRedirected");

if (bAfterRedirect  &&  location == 'about:blank') {
    //-- DO WHATEVER YOU WANT WITH THE BLANK/NEW PAGE HERE.
    $("body").append (
        '<h1>This content was added after a GM redirect.</h1>'
    );
}
else if (location != 'about:blank') {
    /*-- If we are on the original target page, signal our next incarnation
        that it was triggered by a redirect.  Then redirect to about:blank.
    */
    GM_setValue ("YouHaveBeenRedirected", true);
    location.assign ("about:blank");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...