I'm trying to write a safari extension, that lets me get the url of the element being clicked on when I open a context menu (similar to how when you open the context menu on a link, and you choose "open link in new window" or something.
Once I have the url in a var I will do something else with it. How do I do that?
I have the following script in my global html file.
<script>
safari.application.addEventListener("command",handleContextMenu,false);
function handleContextMenu(event)
{
if(event.command === "my command")
{
var link = event.target;
// try to get a link element in the parent chain
while(link != null && link.nodeType == Node.ELEMENT_NODE
&& link.nodeName.toLowerCase() != "a")
{
link = link.parentNode;
}
if(link)
{
// do stuff
//I open the window only to check that I am correctly getting the link
var nwin = safari.application.openBrowserWindow();
nwin.activeTab.url = link;
}
}
}
</script>
Instead of opening a page, it opens a window which has [object%20SafariExtensionContextMenuItem]
in the address bar.
How do I fix my code, so that I put the correct url in the address bar ?
event.target
is aSafariExtensionContextMenuItem
, not the page element you are expecting. To get access to the page contents, you will need to use an injected script:global.js
injected.js