javascript - 停止执行 Javascript 函数(客户端)或对其进行调整

标签 javascript greasemonkey

我想停止执行站点中的一行,以便浏览器读取除该行之外的整个页面。或者浏览器可能会简单地跳过该 JavaScript 函数的执行。

或者

有没有办法我可以以某种方式调整javascript,以便javascript中的随机数生成函数不生成随机数,而是生成我想要的数字......

我无权访问托管脚本的网站,因此所有这些都需要在客户端完成。

最佳答案

Firefox 目前支持the beforescriptexecute event (自 Version 4, released on March 22, 2011 起)

随着该事件和 the // @run-at document-start directive 、Firefox 和 Greasemonkey 现在似乎在拦截特定方面做得很好 <script>标签。

这对于 Chrome+Tampermonkey 来说仍然是不可能的。对于除 Firefox+Greasemonkey 之外的任何内容,您将需要使用下面其他答案中所示的技术来编写完整的浏览器扩展。

The checkForBadJavascripts function封装了这一点。例如,假设页面有 <script>像这样的标签:

<script>
    alert ("Sorry, Sucka!  You've got no money left.");
</script>

您可以使用checkForBadJavascripts像这样:

checkForBadJavascripts ( [
    [   false, 
        /Sorry, Sucka/, 
        function () {
            addJS_Node ('alert ("Hooray, you\'re a millionaire.");');
        } 
    ]
] );

获得更好的消息。 (^_^)
有关更多信息,请参阅 checkForBadJavascripts 中的内联文档。

<小时/>

要查看完整脚本的演示,请首先访问this page at jsBin 。您将看到 3 行文本,其中两行是由 JS 添加的。

现在,install this script (View source;也在下面。)并重新访问该页面。您将看到 GM 脚本删除了一个坏标签,并用我们的“好”JS 替换了另一个标签。

<小时/>

请注意,只有 Firefox 支持 beforescriptexecute事件。它已从 HTML5 规范中删除,且未指定等效功能。

<小时/> <小时/>

完整的GM脚本示例(与GitHub和jsBin相同):

给定这个 HTML:

<body onload="init()">
<script type="text/javascript" src="http://jsbin.com/evilExternalJS/js"></script>
<script type="text/javascript" language="javascript">
    function init () {
        var newParagraph            = document.createElement ('p');
        newParagraph.textContent    = "I was added by the old, evil init() function!";
        document.body.appendChild (newParagraph);
    }
</script>
<p>I'm some initial text.</p>
</body>


使用这个 Greasemonkey 脚本:

// ==UserScript==
// @name        _Replace evil Javascript
// @include     http://jsbin.com/ogudon*
// @run-at      document-start
// ==/UserScript==

/****** New "init" function that we will use
    instead of the old, bad "init" function.
*/
function init () {
    var newParagraph            = document.createElement ('p');
    newParagraph.textContent    = "I was added by the new, good init() function!";
    document.body.appendChild (newParagraph);
}

/*--- Check for bad scripts to intercept and specify any actions to take.
*/
checkForBadJavascripts ( [
    [false, /old, evil init()/, function () {addJS_Node (init);} ],
    [true,  /evilExternalJS/i,  null ]
] );

function checkForBadJavascripts (controlArray) {
    /*--- Note that this is a self-initializing function.  The controlArray
        parameter is only active for the FIRST call.  After that, it is an
        event listener.

        The control array row is  defines like so:
        [bSearchSrcAttr, identifyingRegex, callbackFunction]
        Where:
            bSearchSrcAttr      True to search the SRC attribute of a script tag
                                false to search the TEXT content of a script tag.
            identifyingRegex    A valid regular expression that should be unique
                                to that particular script tag.
            callbackFunction    An optional function to execute when the script is
                                found.  Use null if not needed.
    */
    if ( ! controlArray.length) return null;

    checkForBadJavascripts      = function (zEvent) {

        for (var J = controlArray.length - 1;  J >= 0;  --J) {
            var bSearchSrcAttr      = controlArray[J][0];
            var identifyingRegex    = controlArray[J][1];

            if (bSearchSrcAttr) {
                if (identifyingRegex.test (zEvent.target.src) ) {
                    stopBadJavascript (J);
                    return false;
                }
            }
            else {
                if (identifyingRegex.test (zEvent.target.textContent) ) {
                    stopBadJavascript (J);
                    return false;
                }
            }
        }

        function stopBadJavascript (controlIndex) {
            zEvent.stopPropagation ();
            zEvent.preventDefault ();

            var callbackFunction    = controlArray[J][2];
            if (typeof callbackFunction == "function")
                callbackFunction ();

            //--- Remove the node just to clear clutter from Firebug inspection.
            zEvent.target.parentNode.removeChild (zEvent.target);

            //--- Script is intercepted, remove it from the list.
            controlArray.splice (J, 1);
            if ( ! controlArray.length) {
                //--- All done, remove the listener.
                window.removeEventListener (
                    'beforescriptexecute', checkForBadJavascripts, true
                );
            }
        }
    }

    /*--- Use the "beforescriptexecute" event to monitor scipts as they are loaded.
        See https://developer.mozilla.org/en/DOM/element.onbeforescriptexecute
        Note that it does not work on acripts that are dynamically created.
    */
    window.addEventListener ('beforescriptexecute', checkForBadJavascripts, true);

    return checkForBadJavascripts;
}

function addJS_Node (text, s_URL, funcToRun) {
    var D                                   = document;
    var scriptNode                          = D.createElement ('script');
    scriptNode.type                         = "text/javascript";
    if (text)       scriptNode.textContent  = text;
    if (s_URL)      scriptNode.src          = s_URL;
    if (funcToRun)  scriptNode.textContent  = '(' + funcToRun.toString() + ')()';

    var targ = D.getElementsByTagName ('head')[0] || D.body || D.documentElement;
    //--- Don't error check here. if DOM not available, should throw error.
    targ.appendChild (scriptNode);
}

关于javascript - 停止执行 Javascript 函数(客户端)或对其进行调整,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24972416/

相关文章:

javascript - Greasemonkey 脚本来监控网站更改

javascript - 使用枚举形式 setInterval() 导致异常?

javascript - promise.all() 中的 setState react

JavaScript/CodeMirror - 刷新文本区域

javascript - xpath - 限制搜索到节点不工作?

javascript - 检测XHR请求

javascript - 编写 .js 函数时遇到的问题

javascript - app.post 不工作! "Cannot GET/up"

javascript - 内置 JavaScript/Greasemonkey 函数来获取服务器时间?

javascript - 无法在新 (AJAX) 窗口中通过 ID、类名等访问元素?