1

Ниже приведен код работы контекстного меню расширения. Например я кликаю в текстовый 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);

1 ответ 1

0

Придётся ставить слушатель на событие click (правой кнопкой) в content-script. При наступлении события передавать информацию об элементе в background.

Также ставим слушатель в background на клик в context-menu. При наступлении события у нас уже есть в background информация о необходимом элементе.

Нечто похожее можно увидеть здесь: content-script, background. Там создаются необходимые пункты меню при каждом нажатии правой кнопкой мышки на страницах, и соответственно обрабатываются по-разному.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.