Search code examples
javascriptgoogle-chromeuserscripts

Google Chrome - Uncaught TypeError: Cannot call method 'getElementsByClassName' of null


I have been trying to write my first user script for Google Chrome. It check the router page and reconnect until it gets a valid IP address.

I saved the script as IPchecker.user.js and installed it in google chrome via extensions page. But when I refresh the page, the javascript console throw an error:

Uncaught TypeError: Cannot call method 'getElementsByClassName' of null 

From my understanding, this means that it does not know what document is. But how could this happen? I thought the script will be run AFTER the document has been ready? Is it not true? Here's the code which works in javascript console.

// ==UserScript==  
// @name         WAN checker
// @version      0.0.1
// @description  Check tomato IP addresses and reconnect as needed
// @match        *://192.168.1.1/status-overview.asp
// ==/UserScript== 

(function reconnect() {
    wan1ip = document.getElementById('wan1ip').getElementsByClassName('content')[0].innerText.split('.').slice(0,2).join('.');

    if (wan1ip != "333.3333") {
    wan_connect("1");
    setTimeout("reconnect()",2000);
    }
    wan2ip = document.getElementById('wan2ip').getElementsByClassName('content')[0].innerText.split('.').slice(0,2).join('.');
if (wan2ip != "333.333") {
    wan_connect("2");
    setTimeout("reconnect()",2000);
    }
})();

Solution

  • You're not calling it on document. You're calling it on

     document.getElementById('wan1ip')
    

    Make sure the element exists.

    For testing, you can break it up and do

    container = document.getElementById('wan1ip');
    console.log(container, container.getElementsByClassName('content'));
    

    That will show you what element you're doing getElementsByClassName on and then whatever elements of that class it finds in it. I bet the first one will be null.

    This will also work but probably won't get you the result you're looking for:

    document.getElementsByClassName('content')