Question

I want to write a plugin that translate user-selected text. But I stalled on "getting the selected text". I tried a lot of options, but none of them does not work (probably my fault).

Now my global.html looks like this:

<script >

// Set up Listener(s)
safari.application.addEventListener("command", performCommand, false);  

// Functions to perform when event is received
function performCommand(event) {
    if (event.command === "contextmenutranslate") {
        alert("first");
        alert(window.getSelection());
    }
}

</script>

Second alert returns empty string.
What am I doing wrong?
What should i do?

Was it helpful?

Solution

The global page cannot interact with any web pages directly for security reasons. So, to get selected text from a page, you need to use an injected script. You can then use messages to communicate between your global page and the injected script.

For example:

global.js

safari.application.addEventListener('command', performCommand, false);
safari.application.addEventListener('message', handleMessage, false);

function performCommand(event) {
    if (event.command === 'contextmenutranslate') {
        safari.application.activeBrowserWindow.activeTab.page.dispatchMessage('getselection');
    }
}

function handleMessage(msg) {
    if (msg.name === 'theselection') {
        alert(msg.message);
    }
}

injected.js

safari.self.addEventListener('message', handleMessage, false);

function handleMessage(msg) {
    if (msg.name === 'getselection') {
        var sel = window.getSelection()+'';
        safari.self.tab.dispatchMessage('theselection', sel);
    }
}

Remember to set injected.js as a start or end script in the Safari Extension Builder.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top