@BulatDos

Почему не работает обмен сообщениями в Chrome Extension?

Привет всем, пишу хром расширение. В расширении я задаю параметры настроек работы скрипта, в background.js пишу отправку:
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
                    chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
                    console.log(response.farewell);
                    });
                });

Получаю ошибку в popup.html :
Error in event handler for (unknown): TypeError: Cannot read property 'farewell' of undefined
at chrome-extension://pkeodebpncilhjkihpmkpkinjocodfdh/background.js:33:41handler @ extensions::uncaught_exception_handler:8exports.handle @ extensions::uncaught_exception_handler:100EventImpl.dispatch_ @ extensions::event_bindings:376EventImpl.dispatch @ extensions::event_bindings:393target.(anonymous function) @ extensions::SafeBuiltins:19publicClass.(anonymous function) @ extensions::utils:94dispatchOnDisconnect @ extensions::messaging:302


Есть файл injection.js который я встраиваю в удаленный сайт через onLoad(), пишу там приемник настроек:
chrome.runtime.onMessage.addListener(
        function(request, sender, sendResponse) {
        console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");
        if (request.greeting == "hello")
            sendResponse({farewell: "goodbye"});
    });

При загрузке начинает ругаться:
Uncaught TypeError: Cannot read property 'addListener' of undefined


Что я делаю не так?

Заранее спасибо!
  • Вопрос задан
  • 4736 просмотров
Решения вопроса 1
@BulatDos Автор вопроса
Все разобрался, на стороне инжекшена:
var editorExtensionId = "dkjkabjbiklebdaljhmpflnnjgibpbgh";
	chrome.runtime.sendMessage(editorExtensionId, {greeting: "hello"},
	  function(response) {
		console.log(response.farewell);
	  });

На стороне background.js прямо в корне:
chrome.runtime.onMessageExternal.addListener(
		function(request, sender, sendResponse) {
		console.log(sender.tab ?
					"from a content script:" + sender.tab.url :
					"from the extension");
		if (request.greeting == "hello")
		  sendResponse({farewell: "goodbye"});
		}
		);


Единственное что желательно при запросе с инжекшена сделать вызов по таймауту, а то в зависимости от канала.
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
In4in
@In4in
°•× JavaScript Developer ^_^ ו°
Может быть, я скажу глупость, но вы параметры местами перепутали.

ReUPD:
function(sender, request, sendResponse) {...}
Ответ написан
Ваш ответ на вопрос

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

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