Q:

DOM Not Loading In Chrome App

I have a simple HTML5 Snake game that uses canvas that I want to package as a Chrome App. Here is my normal HTML file:
<!DOCTYPE html>
<html>
    <head>
        <title>Snake</title>
        <link rel="stylesheet" href="snake.css">
    </head>
    <body>
        <canvas id="canvas" width="700" height="700"></canvas>
        <script type="text/javascript" src="food.js"></script>
        <script type="text/javascript" src="snake.js"></script>
        <script type="text/javascript" src="point.js"></script>
        <script type="text/javascript" src="game.js"></script>
        <script type="text/javascript">
            window.onload = function() {
                    var canvas = document.getElementById("canvas"),
                    game = new Game(canvas, new Snake(canvas), new Food(canvas));
                game.init();
                game.run();
            }
        </script>
    </body>
</html>

However the script in the HTML is not allowed. So I removed it and placed it main.js which creates the window. I provide a callback that is the same as window.onload above because my understanding is that this is the chrome app equivalent:
chrome.app.runtime.onLaunched.addListener(function() {
    "use strict";
    chrome.app.window.create('snake.html', {
        bounds: {
            width: 800,
            height: 800
        }
    }, function() {
        var canvas = document.getElementById("canvas"),
            game = new Game(canvas, new Snake(canvas), new Food(canvas));
        game.init();
        game.run();
    });
});

This runs after the DOM appears to have loaded but document.getElementById always returns null. Looking at the document in the developer tools it looks like only the scripts are loaded even though I can see the canvas in the app window (I have a border around the canvas). Can anyone tell me what is going on? Where is the appropriate place to access the DOM from when window.onload doesn't work?

A:

main.js is running on the background / event page and is not in the same context as the newly created window's DOM. You can interact with that context as documented on the create callback, but it's not how I recommend solving this.
Instead, from your main.js simply create the window, and from the HTML file load script code that executes directly.
window.html:
<!DOCTYPE html>
<html>
    <body>
        <canvas id="canvas" width="700" height="700"></canvas>
        <script ...</script>
        <script type="text/javascript" src="window.js"></script>

window.js:
var canvas = document.getElementById("canvas"),
game = new Game(canvas, new Snake(canvas), new Food(canvas));
game.init();
game.run();

