我一直在尝试为Google Chrome编写我的第一个用户脚本。它检查路由器页面并重新连接,直到它获得有效的IP地址。
我将脚本保存为IPchecker.user.js,并通过扩展程序页面将其安装在Google Chrome中。但是当我刷新页面时,javascript控制台会抛出一个错误:
Uncaught TypeError: Cannot call method 'getElementsByClassName' of null
根据我的理解,这意味着它不知道什么是文档。但这怎么可能发生呢?我以为脚本将在文档准备好后运行?这不是真的吗?这是在javascript控制台中运行的代码。
// ==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);
}
})();
答案 0 :(得分:3)
你没有在document
上调用它。你在
document.getElementById('wan1ip')
确保元素存在。
进行测试,您可以将其分解并执行
container = document.getElementById('wan1ip');
console.log(container, container.getElementsByClassName('content'));
这将显示你正在做什么元素getElementsByClassName
,然后是它在其中找到的那个类的任何元素。我打赌第一个将为空。
这也可以,但可能无法获得您正在寻找的结果:
document.getElementsByClassName('content')