简体   繁体   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)

I'm having trouble with a simple task.我在做一个简单的任务时遇到了麻烦。 In Xcode 13, you can create a Safari Extension App (Safari Web Extension for iOS 15).在 Xcode 13 中,您可以创建一个 Safari 扩展应用程序(Safari Web Extension for Z1BDF605091920DBZ11FCBD155091920DBZ11)

From looking around, the Shared Extension has various js resources: background.js, content.js, and popup.js.环顾四周,共享扩展有各种 js 资源:background.js、content.js 和 popup.js。

Popup.js is the presented modal when you launch your Safari web extension. Popup.js 是您启动 Safari web 扩展时呈现的模式。 In popup.html, you can add elements to the popup DOM (such as text, button, etc).在 popup.html 中,您可以向弹出 DOM 添加元素(例如文本、按钮等)。 In my popup, I have a button which I have wired up in popup.js.在我的弹出窗口中,我有一个在 popup.js 中连接的按钮。 When I press this button, I want to notify content.js of this event.当我按下这个按钮时,我想通知 content.js 这个事件。 How do I do this?我该怎么做呢?

My current code adds an event listener to the button containing browser.runtime.sendMessage({ type: "start" });我当前的代码向包含browser.runtime.sendMessage({ type: "start" });的按钮添加了一个事件监听器。 in popup.js.在 popup.js 中。

Xcode's template includes the following in content.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);
});

As far as I can tell, the JS is running in popup.js, but I am not seeing anything in console.log for content.js.据我所知,JS 在 popup.js 中运行,但我在 console.log 中没有看到 content.js 的任何内容。 Sidenote: console.log is really hard to use for iPhone Safari app.旁注:console.log 真的很难用于 iPhone Safari 应用程序。

I've found this documentation , but it only discusses passing message from macOS app to JS.我找到了这个文档,但它只讨论了将消息从 macOS 应用程序传递到 JS。 I'm trying to pass message from iOS popup to content.js.我正在尝试将消息从 iOS 弹出窗口传递到 content.js。

See if this works看看这是否有效

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