My problem appears to be quite similar to this problem: Document.querySelector returns null until element is inspected using DevTools, however there are some significant differences that are quite confusing and suggest that the problem may be different.
I’m trying to write code that replaces text in the input box on Google Chat, so I am using document.querySelector. The input field that I need is actually a div
with contenteditable=true
, so I have the following code:
document.querySelector('div[contenteditable]');
This code returns null in the browser console initially until the element has been clicked on in the inspector (clicking on the element in the inspector and using the inspector cursor yield the same result). The element clearly exists as I can type text into it, and the inspector shows that it exists with all properties I am querying for (even before clicking on it in the inspector), despite the fact that the query returns null. Clicking on the element with the inspector will immediately fix this.
Additionally (I’m not sure if this is relevant but it seems like it may suggest something as to the nature of the problem), even once clicking on the element in the inspector such that the query returns an element, the results of that query cannot be stored in a variable.
Advertisement
Answer
I had similar problem and what helped me was Get element from within an iFrame
Depending on your use case, you might want to switch the “context” of your console inputs… at least for the code testing purpose this might be useful and will not produce “null” results. (Image example included at the bottom)
However, please note that accessing iframe with different domain is not possible.
When using document.querySelector(".aAtlvd.bl").contentWindow.document
I am getting this message:
Uncaught DOMException: Blocked a frame with origin “https://mail.google.com” from accessing a cross-origin frame.
For which you are going to need solution from SecurityError: Blocked a frame with origin from accessing a cross-origin frame Which is basically disabling part of your browser security policies.