WebExtensions: How to send a message to content script? (Android)

假如想象 提交于 2019-12-08 22:34:03

问题


I just noticed that the tabs API is only available for the desktop not for Android. In the past I have used this code to send messages to my content scripts:

sendMsgToTabs(msg) {
    return browser.tabs.query({}).then(tabs => {
        let msgPromises = []
        for (let tab of tabs) {
            let msgPromise = browser.tabs.sendMessage(tab.id, msg)
            msgPromises.push(msgPromise)
        }
        return Promise.all(msgPromises)
    })
}

But how am I supposed to do that when the tabs API is not available?
I mean the only thing I can think of is to constantly send empty messages from the content scripts to the background script and whenever the background script has new information then it can send a direct response to one of these messages. But that sounds horribly inefficient. There must be a better way, right?


回答1:


As of Firefox 54, use .tabs.sendMessage()

As of Firefox 54, the tabs API is supported on Firefox for Android.

Alternative for versions of Firefox prior to Firefox 54.

The storage API is stated as supported in Firefox for Android. Thus, while I have not tested it, a method you could use to send data to content script would be to save a value using chrome.storage.local.set(). By listening to the chrome.storage.onChanged event in your content script(s), you can then be notified of that data being stored/changed. This will provide an event driven way to send a message (i.e. stored data) to the content script.

In order to differentiate between receiving the data in different tabs, you will need to establish a protocol for what the data you save means. This could be as simple as just a particular saved key/value meaning that all content scripts should send a message to the background script to get more information, or more complex where you send/store something like:

{
    contentScriptMessage: {
        tab: 14,
        frame: 1234,
        message: 'Some data'
    }
}

In each content script's chrome.storage.onChanged listener, it can then ignore any changes that are not to the tab/frame in which it is running.

This methodology will require fleshing out as you try to implement it. Hopefully, at least part of the chrome.tabs API will be implemented for Android in the near future.



来源:https://stackoverflow.com/questions/41833496/webextensions-how-to-send-a-message-to-content-script-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!