停止执行Javascript函数(客户端)或调整它 [英] Stop execution of Javascript function (client side) or tweak it

查看:208
本文介绍了停止执行Javascript函数(客户端)或调整它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想停止从站点执行一行,以便除了该行之外,浏览器会读取整个页面。或者浏览器可能只是跳过该javascript函数的执行。

I want to stop the execution of one single line from a site, so that the whole page is read by the browser except that single line. Or the browser may simply skip the execution of that javascript function.

OR

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

Is there way i can tweak the javascript somehow so that the random number generating function in javascript do not generate random number, but the numbers i want...

我无权访问该网站脚本是托管所以这一切都需要在客户端完成。

I dont have access to the site on which the script is hosted so all this needs to be done client side.

推荐答案

Firefox目前支持 beforescriptexecute 事件(截至第4版,2011年3月22日发布

Firefox currently supports the beforescriptexecute event (as of Version 4, released on March 22, 2011).

通过该事件和 // @ run-at document-start 指令,Firefox和Greasemonkey现在似乎做得很好接受特定的< script> 标记。

With that event and the // @run-at document-start directive, Firefox and Greasemonkey now seem to do a good job intercepting specific <script> tags.

Chrome + Tampermonkey 仍然无法做到这一点。除了Firefox + Greasemonkey之外,您还需要使用下面其他答案中所示的技术来编写完整的浏览器扩展名。

This is still not possible for Chrome+Tampermonkey. For anything but Firefox+Greasemonkey, you will need to use techniques as shown in the other answers, below, of write a full browser extension.

checkForBadJavascripts 函数封装了这个。例如,假设该页面具有< script> 标记,如下所示:

The checkForBadJavascripts function encapsulates this. For example, suppose the page had a <script> tag like so:

<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 中的内联文档。

to get a much nicer message. (^_^)
See the inline documentation, in checkForBadJavascripts, for more.

要在完整的脚本中查看演示,请首先访问此页面的jsBin 。您将看到3行文本,其中两行由JS添加。

To see a demonstration in a complete script, first visit this page at jsBin. You will see 3 lines of text, two of them added by JS.

现在,安装此脚本查看源 ;它也在下面。)并重新访问该页面。你会看到GM脚本删除了一个坏标签,用我们的好JS替换了另一个。

Now, install this script (View source; it's also below.) and revisit the page. You will see that the GM-script deleted one bad tag and replaced another with our "good" JS.

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

Note that only Firefox supports the beforescriptexecute event. And it was removed from the HTML5 spec with no equivalent capability specified.

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

Complete GM script example (The same as the one at GitHub and 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脚本:


Use this Greasemonkey script:

// ==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函数(客户端)或调整它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆