views:

185

answers:

1

Hi!

I'm trying to build a safari extenstion (mostly for learning purposes) that creates a delicious bookmark, when the user right clicks on a link. I've watched the WWDC Creating a Safari Extension video and everything is working fine.

Except that i don't have a clue how to find out if the user clicked on a link (or just some text) and if so, get it's url and title. What i got so far is this:

document.addEventListener("contextmenu", handleContextMenu, false);
function handleContextMenu(event){
    safari.self.tab.setContextMenuEventUserInfo(event,getSelection().toString());
}

But this obviously only gives me a string of the selection. Now, according to the Safari Reference Library getSelection() returns a DOMSelection object. But even there i'm not able to spot a method that gives me a handle on the selected link.

As you might notice, i'm fairly new to this whole javascript and DOM stuff, so please excuse if this is an obvious question :)

Ciao, Sven

A: 

On a simple right-click, the selection will be set inside the anchor link. This means you will have its text node selected, but the link node itself won't be. Therefore, it's useless to try to find a link inside a selection.

You can use DOMSelection's focusNode to get the last selected text node and check its ancestors until you wind up to an <a> element. That should do about what you want.

var link = null;
var currentElement = event.getSelection().focusNode;
while (currentElement != null)
{
    if (currentElement.nodeType == Node.ELEMENT_NODE && currentElement.nodeName.toLowerCase() == 'a')
    {
        link = currentElement;
        break;
    }
    currentElement = currentElement.parentNode;
}
// link is now an <a> element if the user selected a link's contents
zneak