Home Ask Login Register

Developers Planet

Your answer is one click away!

Bruno Golosio February 2016

App background script, accessing elements of opened window

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() {
      {'outerBounds': {'width': 600, 'height': 500 }},
      function(myWin) {
          myWin.contentWindow.document.getElementById('areaId').value='New text!';

and this is windows.html:

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

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?


Xan February 2016

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).

Post Status

Asked in February 2016
Viewed 2,624 times
Voted 6
Answered 1 times


Leave an answer

Quote of the day: live life