在 chrome 扩展上下文菜单中获取选择 DOM [英] Get Selection DOM in chrome extension contextmenu

查看:30
本文介绍了在 chrome 扩展上下文菜单中获取选择 DOM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试获取我在 Chrome 扩展程序中通过 ContextMenu 选择的 DOM.

I try to get the DOM I select by ContextMenu in Chrome Extension.

代码:

chrome.contextMenus.onClicked.addListener(function(info, tab){
  // the info.selectionText just the text, don not contains html.
});

chrome.contextMenus.create({
  title: "Demo",
  contexts: ["selection"],
  id: "demo"
});

但 info.selectionText 不包含 HTML DOM.有什么方法可以在 Chrome 扩展 contextMenu 中获取选择 dom?.请建议.谢谢.

but the info.selectionText don't contains the HTML DOM. Is there any way to get the selection dom in Chrome extension contextMenu?. Please suggest. thanks.

推荐答案

要访问选择,您需要注入一个 内容脚本 进入页面.

To access the selection, you will need to inject a content script into the page.

在那里,您可以调用 getSelection() 以获取 Selection 对象 并使用其中的范围来提取您需要的 DOM.

There, you can call getSelection() to get a Selection object and play with ranges in it to extract the DOM you need.

// "activeTab" permission is sufficient for this:
chrome.contextMenus.onClicked.addListener(function(info, tab){
  chrome.tabs.executeScript(tab.id, {file: "getDOM.js"})
});

getDOM.js:

var selection = document.getSelection();
// extract the information you need
// if needed, return it to the main script with messaging

您可能需要查看消息传递文档.

这篇关于在 chrome 扩展上下文菜单中获取选择 DOM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆