【问题标题】:Google Chrome - Uncaught TypeError: Cannot call method 'getElementsByClassName' of nullGoogle Chrome - 未捕获的类型错误:无法调用 null 的方法“getElementsByClassName”
【发布时间】:2012-10-12 20:35:47
【问题描述】:

我一直在尝试为 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);
    }
})();

【问题讨论】:

    标签: javascript google-chrome userscripts


    【解决方案1】:

    您不会在 document 上调用它。您正在调用它

     document.getElementById('wan1ip')
    

    确保元素存在。

    为了测试,你可以把它拆开来做

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

    这将向您显示您在 getElementsByClassName 上正在执行的元素,然后显示它在其中找到的该类的任何元素。我敢打赌第一个将是空的。

    这也可以,但可能不会得到你想要的结果:

    document.getElementsByClassName('content')
    

    【讨论】:

    • 哇!确实。它实际上是“wanip”而不是“wan1ip”。我花了2个小时没有找到它。谢谢。
    猜你喜欢
    • 2012-09-07
    • 2013-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-03
    • 1970-01-01
    • 1970-01-01
    • 2014-01-05
    相关资源
    最近更新 更多