Search code examples
javascriptgoogle-chromecross-browsergreasemonkeyuserscripts

Userscript works in Firefox, but Chrome gives: Uncaught TypeError: Cannot read property 'length' of null


I tried to run this script in Chrome, but it doesn't work.

Just the error Cannot read property 'length' of null appears.

if($("div.diashow").length>0&&$("div.diashow.list").length==0){

    jQuery.ajaxSetup({async:false});

    var objContent = $("#objectContent");

    $("span.prev").remove();
    $("span.next").remove();
    $("p.next").remove();

    $("div.screen img").unwrap();

    var numOfSlides = parseInt($("span.volume").text().substr(11));    

    for(var i=2;i<=numOfSlides;i++){

        $.get("document.URL"+"?_slideNumber="+i, function(data) {

            var slidesCanvas = $("div.slidesCanvas",data);

            $("span.prev",slidesCanvas).remove();
            $("span.next",slidesCanvas).remove();
            $("p.next",slidesCanvas).remove();

            $("div.screen img",slidesCanvas).unwrap();

            objContent.append(slidesCanvas);            
        });       
    }        
}

I tried to fix it by myself, but with my limited javascript knowledge, I wasn't successful. Why does this script not work in Chrome? It works in Firefox.

Sample target page for the script.


Solution

  • That userscript uses @require to load jQuery, which is a good thing.
    However, straight Chrome does not support @require (nor much of Greasemonkey's marvelous features).

    So, to use that script as-is in Chrome, the smart thing to do is to install and use Tampermonkey. Tampermonkey has a number of advantages over a straight Chrome userscript, in ease of use, compatibility, and power.

    If, you do not want to use Tampermonkey, then rewrite the script to use this cross-browser technique for loading jQuery.