How to write safari extension that gets the url being clicked on when opening context menu?

1.4k views Asked by At

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 ?

1

There are 1 answers

7
Matt Swain On BEST ANSWER

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);
}