问题
i'm trying to write JavaScript code for a Gmail extension, and when I'm trying to get the canvas frame I, "getElementById" keeps returning the null
value.
Here is the code I'm using:
var doc2 = document.getElementById('canvas_frame').contentDocument;
I'm getting the following error:
"Uncaught TypeError: Cannot read property 'contentDocument' of null"
How can I solve this?
回答1:
Because the iframe with ID canvas_frame
does not need to exist in Gmail.
To get a reference to the relevant document, you can first try to get a reference to iframe#canvas_frame
, and if that fails, check if the current context is correct:
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
来源:https://stackoverflow.com/questions/14032301/gmail-getelementbyidcanvas-frame-keeps-returning-null-in-google-chrome