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

主宰稳场 提交于 2019-11-29 10:58:49
Brock Adams

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).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!