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.