应用程序与 Web 视图中注入的脚本之间的通信

Communication between App and injected script in a webview

本文关键字:脚本 之间 通信 注入 Web 视图 应用程序      更新时间:2023-09-26

我的后台脚本使用webview.executescript(injected.js)方法在应用程序窗口内的 Web 视图中注入脚本。从注入的脚本中,我只需使用 chrome.runtime.sendMessage 即可将消息发送到应用程序。我也想从后台发送消息。我可以使用webview.ContentWindow.postMessage但是如何处理 webview 方面的消息?当 Web 视图收到消息时,我需要执行一些操作。是否可以直接向注入的脚本发送消息?

恐怕在这种情况下无法使用传统的内容脚本chrome.tabs.sendMessage

您有两种方法:

  1. 根据 Chrome 消息传递,您可以在内容脚本和后台之间建立一个 Port 对象。这将允许双向通信,但内容脚本必须启动它。请注意,打开端口将阻止后台卸载为空闲。

  2. 您可以在 Web 视图中注入更多脚本,例如

    function airQuotesMessageWebview(message) {
      webview.executeScript({code: "notReallyMessaging("+JSON.stringify(message)+");"});
    }
    

    这将触发内容脚本中的一些操作。