繁体   English   中英

在 Safari Web Extension (iOS 15) 中从 app (popup.js) 向 JS (content.js) 发送消息

[英]Send message from app (popup.js) to JS (content.js) in Safari Web Extension (iOS 15)

我在做一个简单的任务时遇到了麻烦。 在 Xcode 13 中,您可以创建一个 Safari 扩展应用程序(Safari Web Extension for Z1BDF605091920DBZ11FCBD155091920DBZ11)

环顾四周,共享扩展有各种 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。

看看这是否有效

const isChrome = !window["browser"] && !!chrome;
const browser = isChrome ? chrome : window["browser"];

function sendMessageToContent(message) {
    browser.tabs.query({ active: true }).then(function (currentTabs) {
        if (currentTabs[0].id >= 0) {
            browser.tabs.sendMessage(currentTabs[0].id, message);
        }
    });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM