通过window.location更改URL后如何运行代码?

gal*_*007 1 javascript greasemonkey onload window.location

我正在这样做,但它不起作用:

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

window.location.assign("about:blank");
Run Code Online (Sandbox Code Playgroud)

这是一个 Greasemonkey 脚本。新位置已加载,但警报从未显示。

Bro*_*ams 5

更改后window.location,Greasemonkey 脚本的当前实例将被清除。要在位置更改后“运行代码”,您需要将脚本设置为在新页面上触发(about:blank在本例中),然后使用一个标志来表明通过此脚本重定向原始页面已到达新页面。

  1. 确保脚本@include@match指令在新页面上触发。
  2. 用于GM_setValue()设置标志,让脚本知道它已被故意转世。

这是一个完整的工作脚本,说明了该过程:

// ==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");
}
Run Code Online (Sandbox Code Playgroud)

  • 不,它工作得很好。(1) `document.onLoad` 不是一个有效的函数,(2) 我的答案不使用 onload 函数。**你尝试过我的脚本吗?它有效**(您只需要更改一个包含项,(3)此问题不需要加载(“更改 URL 后运行代码”),(4)窗口加载事件确实会触发,但不需要。 (2认同)