Does chrome.runtime support posting messages with transferable objects?

江枫思渺然 提交于 2019-11-30 05:37:06
Rob W

Messages that go through the extension message passing APIs are always JSON-serialized. This format is not only used for passing messages between background page and content scripts, but also with native applications. So, I guess that it's not very likely that the message passing APIs support more items.

A request for the structured cloning algorithm (more powerful than JSON-serialization, less powerful than transferables) was requested in 2012 already (Chromium issue 112163). The issue is still open; someone has suggested to use a SharedWorker as a "trampoline".

The SharedWorker is affected by the same origin policy, so the callers need to reside at the same origin. To achieve this, you could add a page to web_accessible_resources, and embed this page in a frame.

At the end of this answer, I've attached a bare implementation of a trampoline. Create an extension with these files. Then, open a tab. This tab will contain the embedded frame, and the demo will send a message to the shared worker. This message will be transported to the background page, just view the console of the background page to see these messages.
The demo is minimal, you need to implement the port management (destruction) yourself.
The demo does not use transferable message passing (yet), because it's a general implementation that allows multiple ports. If you ensure that at most two ports exist at the same time, then you could change the code to use transferables (transferables only make sense when there's one received and one sender, because the ownership of the object is also transferred).

Special case: Same-process

If all of your code runs in the same process, then you can use a simpler approach without SharedWorkers.

The same origin policy forbids direct access from/to the frame and the extension, so you will use parent.postMessage to cross this bridge. Then, in the onmessage event of the page, you can use chrome.extension.getViews to get a direct reference to the window object of one of your extension pages (e.g. popup page, options page, ...).
From the other pages, chrome.extension.getBackgroundPage() gives a reference to the window object of the background page (for an event page, use chrome.runtime.getBackroundPage(callback)).

If you want to connect two frames, use the Channel messaging API (see whatwg specification and Opera's dev article). With this method, you'll establish a direct connection between the frames, even if they are located on different origins!

Example: Trampoline

worker.js

var ports = [];
onconnect = function(event) {
    var port = event.ports[0];
    ports.push(port);
    port.start();
    port.onmessage = function(event) {
        for (var i = 0; i < ports.length; ++i) {
            if (ports[i] != port) {
                ports[i].postMessage(event.data);
            }
        }
    };
};

trampoline.js

var worker = new SharedWorker(chrome.runtime.getURL('worker.js'));
worker.port.start();
// Demo: Print the message to the console, and remember the last result
worker.port.onmessage = function(event) {
    console.log('Received message', event.data);
    window.lastMessage = event.data;
};
// Demo: send a message
worker.port.postMessage('Hello');

trampoline.html

<script src="trampoline.js"></script>

contentscript.js

var f = document.createElement('iframe');
f.src = chrome.runtime.getURL('trampoline.html');
f.hidden = true;
(document.body || document.documentElement).appendChild(f);

manifest.json

Note: I put trampoline.js as a background script to save space in this answer. From the perspective of the Web worker, it doesn't matter who initiated the message, so I have re-used the code for sending and receiving messages (it's a simple demo, after all!).

{
    "name": "Trampoline demo",
    "version": "1",
    "manifest_version": 2,
    "background": {
        "scripts": ["trampoline.js"],
        "persistent": true
    },  
    "content_scripts": [{
        "js": ["contentscript.js"],
        "matches": ["<all_urls>"]
    }],
    "web_accessible_resources": [
        "trampoline.html"
    ]   
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!