Search code examples
javascriptfirefoxcopyfirefox-addonfirefox-addon-sdk

Copy to clipboard from Firefox add-on content 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 that I can do this with 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 a content script produces this error:

ReferenceError: require is not defined

To solve this, I think I might need to interact with a page script somehow, but after reading the documentation, I'm still not sure how to do it. Can anyone post sample code or point me in the right direction?


Solution

  • I finally got it to work with onAttach. Here's my 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.');