yarkov
@yarkov
Помог ответ? Отметь решением.

Как получить идентификатор элемента страницы в расширении Google Chrome?

Ниже приведен код работы контекстного меню расширения.
Например я кликаю в текстовый input. Как мне получить его идентификатор, чтобы вывести строку не в alert, а вставить в input?

Все пальцы обгуглил - не нашел решения...

// 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);
  • Вопрос задан
  • 597 просмотров
Пригласить эксперта
Ответы на вопрос 1
@devunion
Ну тут все просто.

Вам надо:
1. Добавить content script, который вставляется во все страницы.
2. В pasteRandom отправить сообщение контент-скрипту с id элементом и нужным текстом.
3. Скопировать insertTextAtCursor в контент-скрипт.
4. В контент-скрипте создать листенер, который будет слушать сообщения с background page и вызывать insertTextAtCursor.

Все.
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы