Copy to clipboard from added Firefox add-on script
I want to write a content script in a Firefox add-on that will copy a string to the user's clipboard in response to an event. I know I can do it using the Firefox Clipboard API like this:
var clipboard = require("sdk/clipboard");
var val = "Lorem ipsum dolor sit amet";
alert('copying "' + val + '" to clipboard');
clipboard.set(val);
But trying to access the clipboard API in the content script throws this error:
ReferenceError: require is not defined
To fix this I think I might need to interact with the script page somehow , but after reading the documentation, I'm still not sure how. Can anyone post a sample code or point me in the right direction?
+3
source to share
1 answer
I finally got it to work with onAttach
. Here's mine main.js
:
var pageMod = require("sdk/page-mod");
var self = require("sdk/self");
var clipboard = require("sdk/clipboard");
pageMod.PageMod({
include: 'example.com',
contentScriptFile: self.data.url('content-script.js'),
onAttach: function(worker) {
worker.port.on('copyToClipboard', function(request) {
clipboard.set(request);
});
}
});
And content-script.js
:
self.port.emit('copyToClipboard', 'This text will be copied.');
+4
source to share