Вопрос по javascript – Изменение Javascript на странице HTML вне моего контроля [дубликат]

4

This question already has an answer here:

Stop execution of Javascript function (client side) or tweak it 4 answers

Я использую HTML-страницу вне моего контроля. Он определяет функцию Javascript во встроенном<script> пометить и вызывает его в<body onload="..."> :

<html>
...
<body onload="init()">
<script type="text/javascript" language="javascript">
    function init() {
        ...
    }
</script>
...

Как я могу изменить эту функцию до ее вызова? Я пытался использовать Greasemonkey для изменения сценария или для вставки другого сценария сразу после него, чтобы переопределить функцию, но, похоже, он не имеет никакого эффекта.

Error: User Rate Limit Exceeded Hawken
Error: User Rate Limit Exceeded palm3D

Ваш Ответ

2   ответа
-1

Error: User Rate Limit ExceededError: User Rate Limit ExceededError: User Rate Limit ExceededscriptError: User Rate Limit ExceededscriptError: User Rate Limit Exceeded@run-atError: User Rate Limit ExceededbeforescriptexecuteError: User Rate Limit Exceeded

var firstScript = document.body.getElementsByTagName('script')[0];
var newScript = document.createElement('script');
var scriptArray = new Array();
scriptArray.push('function init() {');
scriptArray.push('    ...');
scriptArray.push('}');
newScript.innerHTML = scriptArray.join('\n');
scriptArray.length = 0; // free this memory
firstScript.parentNode.insertBefore(newScript, firstScript.nextSibling);

Error: User Rate Limit Exceeded

  • the Error Console to catch the many small errors that you're bound to make. and
  • the Inspect tool to see the resulting HTML (because the regular View Source doesn't show that!).
Error: User Rate Limit Exceeded
10

Error: User Rate Limit ExceededusuallyError: User Rate Limit ExceededError: User Rate Limit Exceededbeforescriptexecute eventError: User Rate Limit Exceeded@run-at document-startError: User Rate Limit ExceededError: User Rate Limit ExceededError: User Rate Limit ExceededВотError: User Rate Limit Exceeded

Error: User Rate Limit Exceededinit()Error: User Rate Limit ExceededcheckForBadJavascripts()Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

//--- New "init" function to replace the bad one.
function init () {
    //... Do what you want here...
}

checkForBadJavascripts ( [
    [false, /function\s+init(/, function () {addJS_Node (init);} ]
] );

Error: User Rate Limit Exceededfunction\s+init(Error: User Rate Limit Exceeded<script>Error: User Rate Limit ExceededaddJS_Node()Error: User Rate Limit Exceeded


Error: User Rate Limit ExceededError: User Rate Limit ExceededError: User Rate Limit Exceeded

Error: User Rate Limit Exceeded<script>Error: User Rate Limit Exceeded

// ==UserScript==
// @name        _Replace evil Javascript
// @include     http://output.jsbin.com/tezoni*
// @run-at      document-start
// @grant       none
// ==/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);
}
Error: User Rate Limit ExceededproperError: User Rate Limit Exceeded
Error: User Rate Limit ExceededcheckForBadJavascriptsError: User Rate Limit Exceeded

Похожие вопросы