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) + ");";
browser.tabs.executeScript({
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, {
code,
});
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?