Search code examples
javascriptgoogle-chromeuserscripts

Uncaught ReferenceError: (function) is not defined


I have been trying to write my first user script for Google Chrome. It checks 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 throws an error:

Uncaught ReferenceError: wan_connect is not defined 

In this case, wan_connect is a function which was defined on the orginal page:

<html>
<head>
<script type="text/javascript">
    function serv(service, sleep)
    {
     form.submitHidden('service.cgi', { _service: service, _redirect: 'status-overview.asp', _sleep: sleep });
    }
    function wan_connect(wanid)
    {
     if (wanid == "1") {
     serv('wan1link-restart', 5);
     }
     if (wanid == "2") {
     serv('wan2link-restart', 5);
     }
    }

    //All other stuff deleted...

</script>
</head>
<body> Also deleted...</body>
</html>

Here is my script. Looks like it does not recognize the function from the original page. Is there a way to call it?

// ==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('wanip').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

  • Yes, you can call that code in a few ways:

    1. Paste the appropriate source code into your script.

      or

    2. Call the original page in an iframe and call the function from there. Same-domain iframes are easier, but this can be done cross-domain as well.

      or

    3. Use GM_xmlhttpRequest() to grab the original page's source code. Extract the appropriate script nodes from the source and inject that code into the current target page.

    All of these approaches have been covered, to some degree in previous and questions.