0

我正在尝试为 Gmail 扩展程序编写 JavaScript 代码,当我尝试获取画布框架时,“getElementById”不断返回null值。

这是我正在使用的代码:

var doc2 = document.getElementById('canvas_frame').contentDocument;

我收到以下错误:

"Uncaught TypeError: Cannot read property 'contentDocument' of null"

我该如何解决这个问题?

4

1 回答 1

2

因为带有 ID 的 iframecanvas_frame不需要存在于 Gmail 中。

要获取对相关文档的引用,您可以先尝试获取对 的引用iframe#canvas_frame,如果失败,请检查当前上下文是否正确:

var doc2 = document.getElementById('canvas_frame');
if (doc2) {
    doc2 = doc2.contentDocument;
} else if (document.getElementById('js_frame')) {
    // If #canvas_frame does not exist, but #js_frame does, then Gmail renders
    // everything in the main (=top) frame
    doc2 = document;
} // else not Gmail's document, and doc2 === null
于 2012-12-25T16:31:26.593 回答