Get Selection DOM in chrome extension contextmenu

前端 未结 2 1500
我寻月下人不归
我寻月下人不归 2020-12-11 09:18

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

Code:

chrome.contextMenus.onClicked.addListener(function(info, tab){
         


        
相关标签:
2条回答
  • 2020-12-11 09:42

    If you want just selected text from context menu than you can do it by following code

    function getClickHandler() {
        return function(info, tab) {
          // info.selectionText contain selected text when right clicking
          console.log(info.selectionText);
        };
      };
    
    
    /**
     * Create a context menu which will only when text is selected.
     */
    chrome.contextMenus.create({
      "title" : "Get Text!",
      "type" : "normal",
      "contexts" : ["selection"],
      "onclick" : getClickHandler()
    });
    
    0 讨论(0)
  • 2020-12-11 09:57

    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.

    0 讨论(0)
提交回复
热议问题