首页 > 解决方案 > 在 Safari Web Extension (iOS 15) 中将消息从应用程序 (popup.js) 发送到 JS (content.js)

问题描述

我在做一个简单的任务时遇到了麻烦。在 Xcode 13 中,您可以创建一个 Safari Extension App(适用于 iOS 15 的 Safari Web Extension)。

环顾四周,共享扩展有各种 js 资源:background.js、content.js 和 popup.js。

Popup.js 是您启动 Safari Web 扩展时呈现的模式。在 popup.html 中,您可以将元素添加到弹出 DOM(例如文本、按钮等)。在我的弹出窗口中,我有一个在 popup.js 中连接的按钮。当我按下这个按钮时,我想通知 content.js 这个事件。我该怎么做呢?

browser.runtime.sendMessage({ type: "start" });我当前的代码向包含在 popup.js中的按钮添加了一个事件侦听器。

Xcode 的模板在 content.js 中包含以下内容:

browser.runtime.sendMessage({ greeting: "hello" }).then((response) => {
    console.log("Received response: ", response);
});

browser.runtime.onMessage.addListener((request, sender, sendResponse) => {
    console.log("Received request: ", request);
});

据我所知,JS 在 popup.js 中运行,但我在 console.log 中没有看到 content.js 的任何内容。旁注:console.log 真的很难用于 iPhone Safari 应用程序。

我找到了这个文档,但它只讨论了将消息从 macOS 应用程序传递到 JS。我正在尝试将消息从 iOS 弹出窗口传递到 content.js。

标签: iosmobile-safarisafari-extensionios15safari-web-extension

解决方案


推荐阅读