0

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

John
  • 645
  • 1
  • 8
  • 23
  • I known window.crypto API,but I think that is partially support,we need much more functions,like Ecc,SM(chinese national crypt standards)。and we don't want it like web static resources,so we can change it's version whenever without user's permision(that's why we want make it as plugin) – John Jan 02 '20 at 07:22
  • To expose functions to the page context the only way is to create a DOM script element: [more info](/a/9517879). – wOxxOm Jan 02 '20 at 07:53

1 Answers1

0

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,
    });
  }
});
Hammad Akhwand
  • 779
  • 1
  • 7
  • 19