title: Chrome apps webview tag - how to inject CSS or JS in time?
body: <p>I'm writing an application which should embed specific website into a <code>&lt;webview&gt;</code> and inject some CSS and JS code to adapt this website for viewing on certain touch-sensitive device.</p>
  
  <p>The problem is that I can't find a way to inject my code when page is loaded, instead the code is injected AFTER the page is rendered and, as result, all modifications become visible.</p>
  
  <p>While code injection perfectly works with chrome extensions and content script (by setting <code>run_at</code> attribute to <code>document_end</code> on manifest.json, this is not the case for webviews. </p>
  
  <p><strong>This is my code:</strong></p>
  
  <p><strong>manifest.json</strong></p>
  
  <pre class="lang-json prettyprint-override"><code>{
    "name": "App",
    "version": "0.0.1",
    "manifest_version": 2,
  
    "app": {
      "background": {
        "scripts": [ "main.js" ]
      }
    },
  
    "permissions": [
      "webview"
    ]
  }
  </code></pre>
  
  <p><strong>main.js</strong></p>
  
  <pre class="lang-js prettyprint-override"><code>chrome.app.runtime.onLaunched.addListener(function() {
    chrome.app.window.create('index.html', { state: "normal" },
      function(win) {
        win.contentWindow.onload = function() {
          var wv = this.document.querySelector('webview');
          wv.addEventListener('contentload', function(e) {
            this.insertCSS({ code: "body { background: red !important; }" });
          });
        }
      }
    );
  });
  </code></pre>
  
  <p><strong>index.html</strong></p>
  
  <pre class="lang-html prettyprint-override"><code>&lt;webview src="https://developer.chrome.com/apps/tags/webview" style="width: 100%; height: 100%;"&gt;&lt;/webview&gt;
  </code></pre>
  
  <p>The same on the Gist: <a href="https://gist.github.com/OnkelTem/ae6877d2d7b2bdfea5ae" rel="nofollow">https://gist.github.com/OnkelTem/ae6877d2d7b2bdfea5ae</a></p>
  
  <p>If you try this app, you will see that only after the webview is loaded and fully rendered my CSS rule is applied and the page background becomes red. In this example I use <strong>contentload</strong> webview event, but I also tried all other webview events: <strong>loadstart</strong>, <strong>loadstop</strong>, <strong>loadcommit</strong> - with no any difference.</p>
  
  <p>I tried also using webview.contentWindow, but this is object is EMPTY all the time, despite <a href="https://developer.chrome.com/apps/tags/webview#property-contentWindow" rel="nofollow">documentation states</a> it should be used.</p>
  
  <p>Any ideas? Is it possible at all?</p>