A
A
Alexey Yarkov2015-09-22 01:03:43
JavaScript
Alexey Yarkov, 2015-09-22 01:03:43

How to get page element id in google chrome extension?

Below is the code for the context menu of the extension.
For example, I click into a text input. How can I get its ID so that I can display the string not in alert, but insert it into input?
I googled all my fingers - I did not find a solution ...

// background.js
function insertTextAtCursor(el, text) {
    var val = el.value, endIndex, range;
    if (typeof el.selectionStart != "undefined" && typeof el.selectionEnd != "undefined") {
        endIndex = el.selectionEnd;
        el.value = val.slice(0, el.selectionStart) + text + val.slice(endIndex);
        el.selectionStart = el.selectionEnd = endIndex + text.length;
    } else if (typeof document.selection != "undefined" && typeof document.selection.createRange != "undefined") {
        el.focus();
        range = document.selection.createRange();
        range.collapse(false);
        range.text = text;
        range.select();
    }
}

function pasteRandom(info, tab) {
  if(info.menuItemId == "c_name"){
    chrome.storage.sync.get("name", function (obj){
      alert(obj.name);
    });
  }
  else if(info.menuItemId == "c_email"){
    chrome.storage.sync.get("email", function (obj){
      alert(obj.email);
    });
  }

  /*alert("item " + info.menuItemId + " was clicked");
  alert("info: " + JSON.stringify(info));
  alert("tab: " + JSON.stringify(tab));*/
}

  
var root = chrome.contextMenus.create({
  title: "Вставить данные из RandomUser" ,
    id: "c_root", 
  contexts:["editable"]
});

var child1 = chrome.contextMenus.create({
  title: "Имя", 
  parentId: root,
  id:"c_name", 
  contexts:["editable"]
});

var child2 = chrome.contextMenus.create({
  title: "Email", 
  parentId: root,
  id:"c_email", 
  contexts:["editable"]
});


//alert("parent:" + root + " child1:" + child1 + " child2:" + child2);

chrome.contextMenus.onClicked.addListener(pasteRandom);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
devunion, 2015-09-22
@devunion

Well, everything is simple.
You need to:
1. Add a content script that is inserted into all pages.
2. In pasteRandom, send a message to the content script with the element id and the desired text.
3. Copy insertTextAtCursor to the content script.
4. In the content script, create a listener that will listen for messages from the background page and call insertTextAtCursor.
All.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question