我的用户脚本仅在刷新页面时使用,或者在iframe上使用,而不是主页面?

Ard*_*rda 5 javascript ajax facebook userscripts

这个简单的代码不适用于Facebook页面.此代码仅在刷新页面时发出警报.如果我用我的鼠标在我的Facebook个人资料中访问该页面; 脚本停止工作.

没有警报或错误.:(
看起来整个脚本不起作用,直到我刷新.

// ==UserScript==
// @name Purge My Facebook
// @namespace http://www.arda.com
// @description test
// @include https://*.facebook.com*
// @include http://*.facebook.com*
// @version 1
// ==/UserScript==
window.setTimeout (isParent, 500);

function isParent () {

    if (window.self == window.top) {
        alert ("main window");
    } else
        window.setTimeout (isParent, 500);
}
Run Code Online (Sandbox Code Playgroud)

除此之外,我还试过这个:

// ==UserScript==
// @name        Purge My Facebook
// @namespace   http://www.arda.com
// @description test
// @include     http://www.facebook.com/*/allactivity*
// @include     https://www.facebook.com/*/allactivity*
// @version     1
// ==/UserScript==

try{
  if (window.self == window.top)
    alert(document.domain+"\nmain window");
  else
    alert(document.domain+"\nin a iframe");
}
catch(e){
  alert(document.domain+"\nHad a problem:\n"+e);
}
Run Code Online (Sandbox Code Playgroud)

Bro*_*ams 8

问题是 AJAX 问题。当您键入 URL 或刷新页面时,您的脚本就会起作用。当您单击“活动日志”按钮时,脚本不会执行此操作。iframe 不是您报告的症状的一个因素。

这是因为单击该链接永远不会加载新页面;它会触发 AJAX 调用来替换部分内容,使其看起来像一个新页面,但事实并非如此。

因此,如果您希望脚本在“新”“主页”上触发,则必须使用类似于此答案中的技术。

对于 Facebook,唯一通常会发生变化的是报告的 URL(但不会触发 hashchange!)和 div 的内容#mainContainer

您还必须@include所有 FB 页面,因为此类页面通常只能通过 AJAX 访问,因此您的脚本需要在上一页https://www.facebook.com/*/allactivity*上运行。

该脚本将解决您的问题中提出的问题:

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


然而, 由于页面大量使用 AJAX,您会发现在页面首次加载时触发几乎总是为时过早。

明智的做法是waitForKeyElements 在您真正关心的页面的特定部分上使用。(问题中没有指出这一点。)

这是一个使用的示例waitForKeyElements请注意,要在 Chrome 中使用@require,您必须使用 Tampermonkey(无论如何您都应该这样做)。