1

I am working on a Chrome App, and I need the background script to access elements of an html window that it creates.

Please do not answer that I can do it from other scripts launched by the created window, because this is not what I need.

This is my background.js file:

chrome.app.runtime.onLaunched.addListener(function() {
   chrome.app.window.create('window.html',
      {'outerBounds': {'width': 600, 'height': 500 }},
      function(myWin) {
          myWin.contentWindow.document.getElementById('areaId').value='New text!';
   }); 
});

and this is windows.html:

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <textarea id="areaId" name="areaId"  rows="4" cols="50">
      This is my text.
    </textarea>
  </body>
</html>

When I launch the app, I get the error:

"Uncaught TypeError: Cannot set property 'value' of null"

I also tried with myWin.document.getElementById(...) and opening the window with var myWin=window.open(...) but without success.

So my question is, how can I access elements of the newly created window from the background script?

2
  • myWin.contentWindow.document should be correct. You should edit your question with that and tell what isn't working and how it isn't working. Commented Feb 8, 2016 at 23:41
  • Thanks, this answers part of my doubts, although I still have an error. I edited my question as you say. Commented Feb 10, 2016 at 9:17

1 Answer 1

2

Okay, so what happens here is wrong timing.

The callback of create executes before the DOM structure of the page is constructed; therefore, getElementById('areaId') doesn't find anything yet.

You can try to hook into the DOMContentLoaded event.

Alternatively, you can go the recommended route and define some functions/variables in that callback that the code in the opened window can then use (docs recommend onload).

Sign up to request clarification or add additional context in comments.

1 Comment

That's interesting, thank you for your answer. Indeed both solutions are suitable for my problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.