Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

Code:

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
286 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

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

You may want to take a look at Messaging docs.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...