文档示例代码报错:newTabBrowser.contentDocument为何为null?
为什么Firefox浏览器控制台示例代码中newTabBrowser.contentDocument为null?
问题场景
运行Firefox浏览器控制台官方文档中的示例代码:
var newTabBrowser = gBrowser.getBrowserForTab(gBrowser.selectedTab); newTabBrowser.addEventListener("load", function() { newTabBrowser.contentDocument.body.innerHTML = "<h1>this page has been eaten</h1>"; }, true); newTabBrowser.contentDocument.location.href = "https://mozilla.org/";
执行后触发以下错误:
Uncaught TypeError: newTabBrowser.contentDocument is null <anonymous> debugger eval code:5 getEvalResult resource://devtools/server/actors/webconsole/eval-with-debugger.js:306 evalWithDebugger resource://devtools/server/actors/webconsole/eval-with-debugger.js:218 evaluateJS resource://devtools/server/actors/webconsole.js:953 evaluateJSAsync resource://devtools/server/actors/webconsole.js:846 makeInfallible resource://devtools/shared/ThreadSafeDevToolsUtils.js:103 debugger eval code:5:1 <anonymous> debugger eval code:5
按照文档说明,该代码应为当前选中标签添加load事件监听以替换页面内容,再加载新页面,但实际触发newTabBrowser.contentDocument为null的类型错误。
原因分析
contentDocument为null的核心原因是当前选中的标签页未完成内容初始化:
- 如果当前标签是刚打开的空白标签,此时标签页还未创建对应的DOM文档对象,直接访问
contentDocument自然返回null。 - 即使标签页已有内容,直接通过
contentDocument.location.href修改地址的操作,可能在浏览器完成标签页内容初始化前执行,导致contentDocument尚未就绪。
另外,原代码直接操作contentDocument.location.href并非Firefox浏览器组件推荐的页面加载方式,这种方式绕开了浏览器的标准加载流程,容易引发未就绪的DOM访问问题。
修复方案
改用Firefox浏览器提供的loadURI方法加载页面,该方法会确保标签页正确初始化内容,并在页面加载完成后触发load事件,此时contentDocument必然已存在。同时在事件回调中使用this代替外部变量,避免闭包引用问题:
var newTabBrowser = gBrowser.getBrowserForTab(gBrowser.selectedTab); newTabBrowser.addEventListener("load", function() { this.contentDocument.body.innerHTML = "<h1>this page has been eaten</h1>"; }, true); // 使用浏览器标准API加载页面 newTabBrowser.loadURI("https://mozilla.org/");
内容的提问来源于stack exchange,提问作者Arthur Dev
相关产品推荐
相关产品推荐

