开发者

Works as javascript, but doesn't work as a Greasemonkey script?

开发者 https://www.devze.com 2023-04-07 22:19 出处:网络
I\'m making a Greasemonkey script to add download links beside videos on cnn.com. I used a saved version of the HTML page to test my script and was able to get it to work perfectly. Then when I put t

I'm making a Greasemonkey script to add download links beside videos on cnn.com.

I used a saved version of the HTML page to test my script and was able to get it to work perfectly. Then when I put the javascript into Greasemonkey and tried it on the actual site, it didn't work.

This is the not the full script, but the part of the script with the problem. It is simply supposed to add a link at the bottom of every div with the "sec_video_box" class (as seen in the picture).

// ==UserScript==
// @name           CNN Download
// @namespace      Cool
// @description    CNN Download
// @include        http://*cnn.c开发者_如何学运维om/video/*
// ==/UserScript==

var getClass = function(clssName, rootNode /*optional*/){

    var root = rootNode || document,
    clssEls = [],
    elems,
    clssReg = new RegExp("\\b"+clssName+"\\b");

    // use the built in getElementsByClassName if available
    if (document.getElementsByClassName){
        return root.getElementsByClassName(clssName);
    }

    // otherwise loop through all(*) nodes and add matches to clssEls
    elems = root.getElementsByTagName('*');
    for (var i = 0, len = elems.length; i < len; i+=1){
        if (clssReg.test(elems[i].className)) clssEls.push(elems[i])
    }

    return clssEls;

};

function insertlinks() { 
    var boxes = getClass("sec_video_box");

    for (i=0; i<boxes.length; i++) { 
            var theboxid = boxes[i].getAttribute("id");
            document.getElementById(theboxid).innerHTML = document.getElementById(theboxid).innerHTML + '<a href="'+ theboxid +'">link</a>';
    } 
}

window.onload = insertlinks ();

Works as javascript, but doesn't work as a Greasemonkey script?

Can someone tell me what I'm doing wrong?


The 3 biggest problems with that script are:

  1. You can't use window.onload that way; see GM Pitfall #2: Event Handlers.   Always use addEventListener() or jQuery.
  2. Those video objects are AJAXed-in after the document loads, anyway.
  3. Those video objects can change, via AJAX; so you'll want to monitor for new objects.

There are some minor issues but first note that the entire existing script can be simplified to this, with jQuery:

// ==UserScript==
// @name            CNN Download
// @namespace       Cool
// @description     CNN Download
// @include         http://*cnn.com/video/*
// @require         http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js
// ==/UserScript==

function insertlinks () {
    var boxes = $(".sec_video_box");

    boxes.each ( function () {
        var theboxid    = this.id;
        $(this).append ('<a href="'+ theboxid +'">link</a>');
    } );
}

$(window).load (insertlinks);

(Important: This sample code will still not work.)




Handling the AJAX issues, it becomes:

// ==UserScript==
// @name            CNN Download
// @namespace       Cool
// @description     CNN Download
// @include         http://*cnn.com/video/*
// @require         http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js
// ==/UserScript==

function insertlink (jNode) {
    var theboxid    = jNode.attr ('id');
    jNode.append ('<a href="' + theboxid + '">link</a>');
}

waitForKeyElements (".sec_video_box", insertlink, false);

function waitForKeyElements (
    selectorTxt,    /* Required: The jQuery selector string that
                        specifies the desired element(s).
                    */
    actionFunction, /* Required: The code to run when elements are
                        found. It is passed a jNode to the matched
                        element.
                    */
    bWaitOnce,      /* Optional: If false, will continue to scan for
                        new elements even after the first match is
                        found.
                    */
    iframeSelector  /* Optional: If set, identifies the iframe to
                        search.
                    */
)
{
    var targetNodes, btargetsFound;

    if (typeof iframeSelector == "undefined")
        targetNodes     = $(selectorTxt);
    else
        targetNodes     = $(iframeSelector).contents ()
                                           .find (selectorTxt);

    if (targetNodes  &&  targetNodes.length > 0) {
        /*--- Found target node(s).  Go through each and act if they
            are new.
        */
        targetNodes.each ( function () {
            var jThis        = $(this);
            var alreadyFound = jThis.data ('alreadyFound')  ||  false;

            if (!alreadyFound) {
                //--- Call the payload function.
                actionFunction (jThis);
                jThis.data ('alreadyFound', true);
            }
        } );
        btargetsFound   = true;
    }
    else {
        btargetsFound   = false;
    }

    //--- Get the timer-control variable for this selector.
    var controlObj      = waitForKeyElements.controlObj  ||  {};
    var controlKey      = selectorTxt.replace (/[^\w]/g, "_");
    var timeControl     = controlObj [controlKey];

    //--- Now set or clear the timer as appropriate.
    if (btargetsFound  &&  bWaitOnce  &&  timeControl) {
        //--- The only condition where we need to clear the timer.
        clearInterval (timeControl);
        delete controlObj [controlKey]
    }
    else {
        //--- Set a timer, if needed.
        if ( ! timeControl) {
            timeControl = setInterval ( function () {
                    waitForKeyElements (    selectorTxt,
                                            actionFunction,
                                            bWaitOnce,
                                            iframeSelector
                                        );
                },
                500
            );
            controlObj [controlKey] = timeControl;
        }
    }
    waitForKeyElements.controlObj   = controlObj;
}

(Which does work.)


window.onload = insertlinks;

Remove the (), they cause the function to run immediately and the return value (null in this case) is assigned to onload. Locally, this is fine since loading is near-instant. Online, however, it will fail.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号