3

I am trying to write javascript code (and put it in a bookmarklet later) that will autofill some textbox on a webpage.

document.getElementById("textboxID").value = "Some Text"

The problem i have seems to be execution context. This code works only if i inspect element first, or if manually change execution context form top to the one selected (ext-gen65). Execution context list (Chrome).

Whats is the (or is there) a proper way to do this?

EDIT: When i use document.getElementById('ext-gen65').contentWindow.document i get Cannot read propery 'document' of undefined error.

Frakula
  • 145
  • 10
  • Possible duplicate of [Get IFrame's document, from JavaScript in main document](https://stackoverflow.com/questions/3999101/get-iframes-document-from-javascript-in-main-document) – CBroe Aug 09 '18 at 10:56
  • Edited the question. – Frakula Aug 09 '18 at 11:10
  • 1
    Might be a timing issue, if you execute this before the iframe has loaded? If that’s not it, then check what `document.getElementById('ext-gen65').contentWindow` returns first - do you get a window instance, or is that null/undefined already? – CBroe Aug 09 '18 at 11:23
  • It does return a window instance. WillhemVanderVeen answer solved it, thanks. – Frakula Aug 09 '18 at 11:36

1 Answers1

2

The problem is that the ID is inside the document of the Iframe, each Iframe has its own window.document property where your element is located. You can get the document in the following manner:

let Iframe =  document.getElementById('yourIframe').contentWindow.document

let value = Iframe.getElementById("textboxID").value = "Some Text"
Willem van der Veen
  • 33,665
  • 16
  • 190
  • 155