My userscript only works when the page is refreshed or on iframes, not the main page?

后端 未结 1 1082
北荒
北荒 2020-12-19 13:12

This simple code doesn\'t work on a Facebook page. This code only alerts when I refresh the page. If I go to that page from my Facebook profile, with my mouse; The script s

相关标签:
1条回答
  • 2020-12-19 13:41

    The problem is an AJAX one. When you type the URL, or refresh the page, your script works. When you click on your "Activity Log" button, the script doesn't. Iframes are not a factor for the symptoms you report.

    This is because clicking that link, never loads a new page; it triggers AJAX calls that replace part of the content, making it look like a new page, but it isn't.

    So, if you want your script to fire on "new" "main pages", you must utilize techniques like those in this answer.

    In the case of Facebook, the only thing that typically changes is the reported URL (but without triggering hashchange!), and the content of the #mainContainer div.

    You must also @include all FB pages because pages like https://www.facebook.com/*/allactivity*are often only reached via AJAX, so your script needed to be running on the previous page.

    This script will solve the problem posed in your question:

    // ==UserScript==
    // @name        Purge My Facebook
    // @namespace   http://www.ardaterekeci.com
    // @description test
    // @include     http://www.facebook.com/*
    // @include     https://www.facebook.com/*
    // @version     1
    // ==/UserScript==
    
    var pageURLCheckTimer = setInterval (
        function () {
            if (    this.lastPathStr  !== location.pathname
                ||  this.lastQueryStr !== location.search
                ||  this.lastPathStr   === null
                ||  this.lastQueryStr  === null
            ) {
                this.lastPathStr  = location.pathname;
                this.lastQueryStr = location.search;
                gmMain ();
            }
        }
        , 222
    );
    
    function gmMain () {
        if (window.self === window.top)
            alert ('"New" main (top) page loaded.');
        else
            alert ('"New" iframed page loaded.');
    }
    


    However, since the page is heavily AJAXed, you'll find that firing when the page first loads will almost always be too early.

    The smart thing to do is to use waitForKeyElements on the specific part of the page that you really care about. (Which was not indicated in the question.)

    Here's an example of using waitForKeyElements. Note that to use @require in Chrome, you have to be using Tampermonkey (which you should be doing anyway).

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