当AJAX在不重新加载页面的情况下更改URL时,如何重新加载Greasemonkey脚本?

时间:2013-09-24 18:32:22

标签: javascript ajax greasemonkey

我有一个应用程序,我正在尝试为其创建Greasemonkey脚本。它利用大量的jQuery和AJAX动态加载内容。

我注意到,每次加载新项目时,网址都会更改,即使页面没有刷新。

每次URL更改时,我是否可以在页面上放置一个重新启动脚本的监听器?

2 个答案:

答案 0 :(得分:16)

如何执行此操作取决于网站/应用程序以及您要执行的操作。 以下是您的选择,最简单,最强大的第一个:

  1. 请勿尝试捕获网址更改。 Use calls to waitForKeyElements() to act on the parts of the various pages that you wanted to manipulate in the first place.这整齐地处理了所有其他方法所固有的一系列时间问题 另见:"Choosing and activating the right controls on an AJAX-driven site"

  2. Just poll for URL changes.这很简单,在实践中运作良好,时间问题比技术#1更少。

  3. 如果网站使用AJAX更改片段(AKA“哈希”),fire on the hashchange event。唉,AJAX网站越来​​越少。

  4. 使用 Mutation Observers 监控<title>代码的更改。 大多数 AJAX页面都足以改变标题。但是,这可能会在加载目标内容之前触发。

  5. Hack into the history.pushState function.这样可以更快地通知页面更改,但95%的时间会在目标元素加载之前触发。你通常还需要一个计时器。此外,它还会在用户脚本环境中引入跨范围问题。


  6. 作为参考,这是一个轮询示例。它仍然是最好的,简单的,跨浏览器,全能的方法:

    /*--- Note, gmMain () will fire under all these conditions:
        1) The page initially loads or does an HTML reload (F5, etc.).
        2) The scheme, host, or port change.  These all cause the browser to
           load a fresh page.
        3) AJAX changes the URL (even if it does not trigger a new HTML load).
    */
    var fireOnHashChangesToo    = true;
    var pageURLCheckTimer       = setInterval (
        function () {
            if (   this.lastPathStr  !== location.pathname
                || this.lastQueryStr !== location.search
                || (fireOnHashChangesToo && this.lastHashStr !== location.hash)
            ) {
                this.lastPathStr  = location.pathname;
                this.lastQueryStr = location.search;
                this.lastHashStr  = location.hash;
                gmMain ();
            }
        }
        , 111
    );
    
    function gmMain () {
        console.log ('A "New" page has loaded.');
        // DO WHATEVER YOU WANT HERE.
    }
    

答案 1 :(得分:0)

“我注意到URL每次都会改变”,很多AJAX会让我发现他们正在使用History API。如果是这种情况,请查看window.onpopstate。这应该使用History API触发每个URL更改。

相关问题