识别 Safari 扩展中上下文菜单事件的链接
我正在尝试构建一个 safari 扩展(主要用于学习目的),当用户右键单击链接时,它会创建一个美味的书签。我观看了 WWDC 创建 Safari 扩展视频,一切正常。
除了我不知道如何查明用户是否单击了链接(或只是一些文本),如果是,则获取它的网址和标题。到目前为止我得到的是这样的:
document.addEventListener("contextmenu", handleContextMenu, false);
function handleContextMenu(event){
safari.self.tab.setContextMenuEventUserInfo(event,getSelection().toString());
}
但这显然只给了我一个选择的字符串。现在,根据 Safari 参考库 getSelection()
返回一个 DOMSelection
对象。但即使在那里,我也无法找到一种方法来为我提供所选链接的句柄。
正如您可能注意到的,我对整个 javascript 和 DOM 内容相当陌生,所以如果这是一个明显的问题,请原谅:)
Ciao, 斯文
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需单击鼠标右键,所选内容就会设置在锚链接内。这意味着您将选择其文本节点,但不会选择链接节点本身。因此,尝试在选择内容中查找链接是没有用的。
您可以使用
DOMSelection
的focusNode
获取最后选定的文本节点并检查其祖先,直到找到元素。这应该可以满足你的要求。
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
'sfocusNode
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.zneak的答案对我不起作用,所以我使用
event.target
而不是选择:zneak's answer did not work for me, so I worked with
event.target
instead of the selection: