Search code examples
javascriptgoogle-chrome-extensioncontextmenu

Trouble with using getAttribute()


I need to find the id of the element that holds text that I've selected, and I've been unsuccessful at finding a way to do this. It looks like the problem is with the fact that you can't use a getAttribute method on a window object. I am using a content script that communicates with an event page to carry it out. This is my content script:

let element = window.getSelection().anchorNode;
let finder = element.getAttribute('id');
alert(finder.toString()); //test

This is my event page:

chrome.contextMenus.create({ id: "M", title: "Feature One", contexts: ["selection"] }); 

chrome.contextMenus.create({ id: "ATCB", title: "Feature Two", contexts: ["selection"] }); 

chrome.contextMenus.onClicked.addListener(function(clickData){

  if (clickData.menuItemId == "M" && clickData.selectionText){
    //var one = clickData.selectionText;
    chrome.tabs.executeScript({
      file: 'contentScript.js'
    });
  }
  if (clickData.menuItemId == "ATCB" && clickData.selectionText){
    var two = clickData.selectionText; 
    alert(two + " two"); //test 
  }

});

And this is my manifest file:

{
    "manifest_version": 2,
  
    "name": "Menu",
    "version": "1.0",
    "icons": {
      "128": "icon.png",
      "48": "icon.png",
      "16": "icon.png"
    },
  
    "browser_action": {
      "default_icon": "icon.png"
    },
  
    "background": {
      "scripts": ["eventPage.js"],
      "persistent": false
    },
  
    "content_scripts": [{
      "matches": ["<all_urls>"],
      "js": ["contentScript.js"] 
    }],
  
    "permissions": [
      "contextMenus",
      "tabs",
      "activeTab",
      "file://*/*",
      "https://*/*",
      "http://*/*"
    ]
  
}

Thank you for reading my question


Solution

  • This can be accomplished with document.activeElement.id; https://www.w3schools.com/jsref/prop_document_activeelement.asp