通过window.location更改URL后如何运行代码? [英] How to run code after changing the URL via window.location?

查看:167
本文介绍了通过window.location更改URL后如何运行代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

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

推荐答案

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

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. 确保脚本的@include@match指令在新页面上触发.
  2. 使用GM_setValue()设置标志,以使脚本知道该脚本是故意转世的.
  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");
}

这篇关于通过window.location更改URL后如何运行代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆