0

I am trying to create a simple safari extension. My current version of Safari is 5.1.7 running in Snow Leopard.

I have 2 documents :

global.html

<!DOCTYPE HTML>
<script>
     safari.application.addEventListener("command", performCommand, false);  


function performCommand(event) {
 if (event.command === "traducir") {
    var query = event.userInfo;
    alert(query);
    query = query.replace(/\s+/g,"+");
    var newTab = safari.application.activeBrowserWindow.openTab();  
    newTab.url = "http://translate.google.es/#en/es/" + query ;
 }
}


</script>

and the injected script : injected.js

document.addEventListener("contextmenu", handleMessage, false);

function handleMessage(msgEvent) {
  var sel = '';
  sel = window.parent.getSelection()+'';
  sel = sel.replace(/^\s+|\s+$/g,"");
  safari.self.tab.setContextMenuEventUserInfo(msgEvent, sel);
}

The extension is very simple :

1- When the user selects one text or word, click right-button and select the item of the contextual menu that raise the function.

2- The injected file gets the value of the selected text and it shared with the global.html through the userInfo.

3- The global.html script open a new tab with the url of google translate.

The problem is that event.userInfo is always NULL. I was searching in Google and all the examples are like this and I don´t know where the problem is and why it returns always NULL.

Pete Carter
  • 2,691
  • 3
  • 23
  • 34
David Villa
  • 107
  • 11
  • Your code works for me. Are you perchance testing on a "file:" URL? Note that extension scripts are not injected in documents with "file:" URLs. By the way, why are you using `window.parent.getSelection` instead of `window.getSelection`? That would not work if the selected text is in an iframe. – chulster Oct 22 '12 at 03:39
  • P.S.-- I am using Safari 6.0.1 on OS X 10.8.2, but I'm not aware of any relevant bugs in Safari 5.1.x. – chulster Oct 22 '12 at 03:46
  • Sorry, i don´t understand "Note that extension scripts are not injected in documents with "file:" URLs." in this case. I have 2 documents : global.html and injected.js and in the safari´s development extension editor, in the tab "START SCRIPTS" i selected "injected.js" that is in the same folder. – David Villa Oct 22 '12 at 18:54
  • I only meant that you should do your testing on a real web page -- which you probably are doing -- not on a page with a URL like "file:///Users/Pete/Documents/test.html". If you test on a file URL, the injected script will not be injected. – chulster Oct 23 '12 at 00:44

1 Answers1

0

This could possibly be due to a too strict setting for "Access Level" in the Extension Builder. Try setting the dropdown menu to "All", and tick the "Include Secure Pages" checkbox.

Matt Swain
  • 3,827
  • 4
  • 25
  • 36