I make an extension for chrome. I need to send a message to background from my content file and get an answer.

I send from content so:

 chrome.runtime.sendMessage({type:'test', method: 'getHtml', data: 'test'}, {}, function (response) { console.log(response); }); 

background message handler:

 chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) { console.log('chrome.runtime.onMessage', request, sender); if(request&&request.type&&request.method) { sendResponse(window[request.type][request.method](request.data)); } }); 

getHtml in background :

 function getHtml (name) { // fetch не работает. let html = fetch('/html/'+name+'.html').then(function(response) { return response.text(); }); return html; // Promise тоже не работает. return $.get('/html/'+name+'.html').then(result => { console.log(result); return result; }); } 

The received data is output to the console, but in response an empty object comes to content .

What am I doing wrong?

Examples are taken from here - do not work

Tritely, this example does not work, but although it is written in the answer to another question:

 function getResult() { var q1 = $.get('/html/test.html'); var q2 = q1.then(function (data) { return data; }); console.log('ffffffff'); return q2; } 

In theory, the request should first work out and then exit the console. But the opposite is happening.

  • Why did you guess to write the then method inside getHtml - but forgot about the existence of this method inside addListener? - Pavel Mayorov
  • @PavelMayorov not quite understand. an example is possible? - Tsyklop
  • @PavelMayorov does not work even an example from a solution from another topic. I added to the cap. - Tsyklop
  • "In theory, the request should first work out and then exit the console." - No, first - the console. The code does not wait for the end of the request, but goes further. - Igor
  • @Igor how can I do what would wait there until the request is executed and return the data? - Tsyklop

1 answer 1

Promises are great for this, you just need to work with them correctly.

background

 chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) { console.log('chrome.runtime.onMessage', request, sender); if (request && request.type && request.method) { window[request.type][request.method](request.data) // вернет Promise .then(function (result) { // ожидаем когда промис выполнится sendResponse(result); // отвечаем на сообщение }) .catch(function (e) { console.log(e); // что-то пошло не так }) } return true; // это обязательно: сообщаем onMessage.addListener что ответ будет ассинхронным }); 

getHtml

 function getHtml (name) { return $.get('/html/'+name+'.html'); }