Question

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 ?

Was it helpful?

Solution

event.target is a SafariExtensionContextMenuItem, not the page element you are expecting. To get access to the page contents, you will need to use an injected script:

global.js

safari.application.addEventListener('command', handleCommand, false);

function handleCommand(event) {
    if(event.command === 'geturl') {
        var link = event.userInfo;
        if (link) {
            safari.application.openBrowserWindow().activeTab.url = link;
        }
    }
}

injected.js

document.addEventListener('contextmenu', handleContextMenu, false);

function handleContextMenu(event) {
    var target = event.target;
    while(target != null && target.nodeType == Node.ELEMENT_NODE && target.nodeName.toLowerCase() != "a") {
        target = target.parentNode;
    }
    safari.self.tab.setContextMenuEventUserInfo(event, target.href);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top