3

I started learning how to program a Safari extension, and unfortunately Apple's Developer Reference pages on that are not really detailed. Hence my question:

Anyone knows how I can pass the text selected by a user in a variable? My extension is a context menu element that needs to use that text the user selects from any webpage.

Thank you very much for your help :)

Anas
  • 866
  • 1
  • 13
  • 23

1 Answers1

1

In your injected script, have a statement like the following:

document.addEventListener('contextmenu', function () {
    safari.self.tab.setContextMenuEventUserInfo(event, window.getSelection());
}, false);

Then, in the command handler of your global script, the selection will be accessible as event.userInfo, so you can use it, for example, like this:

function handleCommand(event) {
    if (event.command == 'myContextMenuCommand') {
        alert('You selected: "' + event.userInfo + '"');
    }
}
chulster
  • 2,809
  • 15
  • 14
  • My script works until I add this line: safari.self.tab.setContextMenuEventUserInfo(event, window.getSelection()); Which prevents the script from even moving on to the next statements.. – Anas Dec 09 '11 at 10:59
  • Try window.getSelection().toString() instead of just window.getSelection(). – chulster Dec 18 '11 at 02:40