Chrome 应用 webview 标签 - 如何及时注入 CSS 或 JS?

Onk*_*tem 4 google-chrome-app

我正在编写一个应用程序,该应用程序应该将特定网站嵌入到 a<webview>并注入一些 CSS 和 JS 代码以适应该网站以在某些触敏设备上查看。

问题是我找不到在页面加载时注入代码的方法,而是在页面呈现后注入代码,因此所有修改都变得可见。

虽然代码注入与 chrome 扩展和内容脚本完美配合(通过在 manifest.json 上设置run_at属性document_end,但 webviews 并非如此。

这是我的代码:

清单文件

{
  "name": "App",
  "version": "0.0.1",
  "manifest_version": 2,

  "app": {
    "background": {
      "scripts": [ "main.js" ]
    }
  },

  "permissions": [
    "webview"
  ]
}
Run Code Online (Sandbox Code Playgroud)

主文件

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; }" });
        });
      }
    }
  );
});
Run Code Online (Sandbox Code Playgroud)

索引.html

<webview src="https://developer.chrome.com/apps/tags/webview" style="width: 100%; height: 100%;"></webview>
Run Code Online (Sandbox Code Playgroud)

要点相同:https : //gist.github.com/OnkelTem/ae6877d2d7b2bdfea5ae

如果你尝试这个应用程序,你会看到只有在 webview 加载并完全呈现后,我的 CSS 规则才会应用,页面背景变成红色。在这个例子中,我使用contentload webview 事件,但我也尝试了所有其他 webview 事件:loadstartloadstoploadcommit - 没有任何区别。

我也尝试过使用 webview.contentWindow,但是这个对象一直是 EMPTY,尽管文档指出它应该被使用。

有任何想法吗?有可能吗?

Rob*_*b W 5

首先,使用loadcommitevent而不是contentloadevent

其次,添加runAt: 'document_start'webview.insertCSS调用中(这也适用于webview.executeScript,如果您想使用它)。的实现executeScript与扩展的 executeScript 实现共享,但不幸的是应用程序文档不完整。看看chrome.tabs.insertCSS直到应用程序文档被修复。

这是一个按需要工作的示例:

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');
        // loadcommit instead of contentload:
        wv.addEventListener('loadcommit', function(e) {
          this.insertCSS({
            code: 'body { background: red !important; }',
            runAt: 'document_start'  // and added this
          });
        });
      }
    }
  );
});
Run Code Online (Sandbox Code Playgroud)

注意:虽然之前的工作,我建议将操作webview的脚本放在index.html中,因为生成的代码更整洁。

// main.js
chrome.app.runtime.onLaunched.addListener(function() {
  chrome.app.window.create('index.html', { state: 'normal' });
});
Run Code Online (Sandbox Code Playgroud)
<!-- index.html -->
<webview src="https://developer.chrome.com/apps/tags/webview" style="width: 100%; height: 100%;"></webview>
<script src="index.js"></script>
Run Code Online (Sandbox Code Playgroud)
// index.js
var wv = document.querySelector('webview');
wv.addEventListener('loadcommit', function() {
  wv.insertCSS({
    code: 'body { background: red !important; }',
    runAt: 'document_start'
  });
});
Run Code Online (Sandbox Code Playgroud)