Gmail getElementById('canvas_frame')保持返回null在谷歌Chrom

Gmail getElementById('canvas_frame') keeps returning null in Google Chrome

本文关键字:返回 null Chrom 谷歌 frame getElementById canvas Gmail      更新时间:2023-09-26

我正在尝试为Gmail扩展编写JavaScript代码,当我试图获得画布框架i时,"getElementById"一直返回null值。

下面是我使用的代码:
var doc2 = document.getElementById('canvas_frame').contentDocument;

我得到以下错误:

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

我该如何解决这个问题?

因为ID为canvas_frame的iframe不需要在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