Search code examples
javascriptencryptiongoogle-chrome-extensionpostmessage

how to send javascript object with postMessage API


I've known node.js has crypto module(use openssl) to do the enc/decrypt(aes,ecc...) job. but don't know how to do it in browser.

so we use the elliptic package,and have pack it in a bundle.js and it worked fine in web.

we want make it a chrome plugin。but I don't know how chrome plugin provide functions to user web page to call from.

I used postMessage in content_script to send messages to user web page, but only can send json data, if I send it with a javascript object (the bundle.js object I pack with many enc functions).It will complains about 'could not be cloned' error。

error


Solution

  • A better approach would be to keep the crypto functions in background.js, and pass data that you want o process via message to background, and have it send back the results to the page.

    For example, if you want to encrypt a selected text, in your content script:

    const encryptText = function (text) {
      return new Promise(function (resolve,reject) {
        chrome.extension.sendMessage({
          method : 'cryptoFunc',
          data : text,
        });
        let tempListener = function (response,sender) {
          if (response.method === 'cryptoFunc_response') {
            resolve(response.data);
            chrome.extension.onMessage.removeListener(tempListener);
          }
        };
        chrome.extension.onMessage.addListener(tempListener);
      });
    };
    let selectedText = window.getSelection().toString();
    encryptText(selectedText).then(function (encrpted) {
      console.log(encrypted);
    });
    

    in your background script:

    chrome.extension.onMessage.addListener(function (request,sender) {
      if (request.method === 'cryptoFunc') {
        let result = cryptoFunc(request.data);
        chrome.tabs.sendMessage(sender.tab.id, {
          method : 'cryptoFunc_response',
          data : result,
        });
      }
    });