Looking for explanation of some example extension code

(Marek Jedlinski) #1

I have created a small extension based on the context-menu-copy-link-with-types example. It works, but there is a bit of magic in background.js I do not understand. In the content script, 'clipboard-helper.js`, there is this function, which does the actual copying:

function copyToClipboard(text, html) { /* .. */ }

However, in background.js, the function is not just called as one might expect. Instead, this is the code to call the function:

// clipboard-helper.js defines function copyToClipboard.
const code = "copyToClipboard(" +
    JSON.stringify(text) + "," +
    JSON.stringify(html) + ");";

    code: "typeof copyToClipboard === 'function';",
}).then((results) => {
    // The content script's last expression will be true if the function
    // has been defined. If this is not the case, then we need to run
    // clipboard-helper.js to define function copyToClipboard.
    if (!results || results[0] !== true) {
        return browser.tabs.executeScript(tab.id, {
            file: "clipboard-helper.js",
}).then(() => {
    return browser.tabs.executeScript(tab.id, {

I understand what is happening here, but I do not understand why. I think I need to get this before I can grok the whole web extension architecture. Why does the function need to be called in such a roundabout way? And why check in this way for whether the function exists? It does exist, we’ve just coded it in clipboard-helper.js. (And if it didn’t, we’d be seeing an error anyway, right?)

Aside from that, could the same effect be achieved easier (or in a more direct manner anyway) by sending a message to the content script?

(erosman) #2

WebExtension doesn’t have a Clipboard API like the legacy or SDK.
There is a new but limited Clipboard API (https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/clipboard) from FF57+

The option is to use a Web API which means faking a content script ‘copy’ by injecting a code into the content page and get the page to copy the data for you (https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Interact_with_the_clipboard).

There has been a LOT of discussion about it.


(Marek Jedlinski) #3

Ah, OK, I get it. So this isn’t how we’ll now be writing all web extension code :slight_smile: Thank you!