Reputation: 333
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);
}
})();
Upvotes: 1
Views: 4259
Reputation: 93613
Yes, you can call that code in a few ways:
Paste the appropriate source code into your script.
or
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
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 userscripts and greasemonkey questions.
Upvotes: 2
Reputation: 413996
No, you can't call a script on one page from another page. You have to include the code in every page that needs to use it.
There are libraries for script loading (RequireJS for example) that can be used to load a script from JavaScript into a page, but you still have to have the script available to be loaded like that.
Upvotes: 1