ken*_*cny 3 javascript google-chrome google-chrome-extension
我尝试获取我ContextMenu在 Chrome 扩展程序中选择的 DOM 。
代码:
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"
});
Run Code Online (Sandbox Code Playgroud)
但 info.selectionText 不包含 HTML DOM。有没有办法在 Chrome 扩展 contextMenu 中获取选择 dom?。请建议。谢谢。
要访问选择,您需要将内容脚本注入页面。
在那里,您可以调用getSelection()以获取一个Selection对象并使用其中的范围来提取您需要的 DOM。
// "activeTab" permission is sufficient for this:
chrome.contextMenus.onClicked.addListener(function(info, tab){
chrome.tabs.executeScript(tab.id, {file: "getDOM.js"})
});
Run Code Online (Sandbox Code Playgroud)
获取DOM.js:
var selection = document.getSelection();
// extract the information you need
// if needed, return it to the main script with messaging
Run Code Online (Sandbox Code Playgroud)
您可能需要查看Messaging 文档。