Skip to content

Instantly share code, notes, and snippets.

@kafene
Created March 10, 2017 13:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kafene/6591a2b35f532eb59c03d2fd841850a3 to your computer and use it in GitHub Desktop.
Save kafene/6591a2b35f532eb59c03d2fd841850a3 to your computer and use it in GitHub Desktop.
Getting the currently selected text in a Firefox extension

Post e10s, this seems to be the most consistent way (should work in both pre and post-e10s builds):

const tabs = require("sdk/tabs");

function getSelectedText() {
    return new Promise(function (resolve, reject) {
        tabs.activeTab.attach({
            contentScript: "self.postMessage(String(getSelection()));",
            onMessage: resolve,
            onError: reject,
        });
    });
}

Then you can use it pretty simply:

getSelectedText().then(text => {
    console.info("SELECTED TEXT =>", text);
});
@Hellboy00000
Copy link

Hello. I am trying for more than 3 weeks to get the selected text in Firefox. Can you explain me how to use this. Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment