0

I am trying to get message from background script to content script and use the value out the function. Here is the codes background.js

var port = null;
var mesaj;
port = chrome.extension.connectNative('_com.test.download_');

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
  
  port.postMessage(request.web_res);
 
  port.onMessage.addListener((response) => {mesaj=response;});
  sendResponse({mesaj});
  console.log(mesaj);   
  }
);

content.js

        for(var i = 0; i < _allImagesList_.length; i++)
        {   
            var address = _allImagesList_[i].src;
            var timestamp = new Date().getTime();
        
            
            var GonderAl=function(response, sender, sendResponse) {
            this.durum= response.mesaj;};
            
            chrome.extension.sendMessage({web_res: _allImagesList_[i].src}, 
            GonderAl.bind(this));
            console.log(durum);
    
            _allImagesList_[i].src=_allImagesList_[i].src+"?i_fix="+timestamp
                

        }

while i run the script, i just see on console the "undefined" value. i got help from this link Scope in chrome message passing

i am not familiar java and chrome extension. i am just trying to learn new.

is there any way to use that value out of the function.

  • Remove all your messaging code (it's for a different thing) and use the [simple messaging examples in the documentation](https://developer.chrome.com/extensions/messaging#simple). – wOxxOm Jun 16 '21 at 09:50
  • @wOxxOm i did read the documentation. as the result of my problem is, codes under content.js file runs at the same time. ```chrome.extension.sendMessage``` and ```console.log(durum)``` are run at the same time. thats why ```durum``` variable is undefined. My solution should be the callback functions. But i am not familiar with java so much. – Kenan Baysal Jun 17 '21 at 06:47
  • 1) `chrome.extension` is an ancient thing, don't use it. 2) JavaScript isn't Java. 3) See the examples in the documentation I've linked. – wOxxOm Jun 17 '21 at 17:08

0 Answers0