0

I am trying to make an chrome-extension. But i have a trouble with returning values out of callback function. Here is my codes; content.js

let filename="block.jpg";
let imgs = document.getElementsByTagName('img');

function iletisim(callback, web_adr){

    chrome.runtime.sendMessage({text: web_adr}, function(response) {

    callback(response);
    }); 
}

function gonder_al(param1){
    console.log("gonder_al ",param1);
    
}

for (imgElt of imgs){
    
    iletisim(gonder_al, imgElt.src);    
    let url = chrome.extension.getURL(filename);
    imgElt.src=url;

};

I want to replace images on the web page under some conditions, which are background.js sends. On this code need to use the callback(response) under the for loop? It seems not possible with sync callback functions but i am not familiar with with java async functions.

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
  • See [this](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) for a *very* similar problem. – Federico klez Culloca Jun 17 '21 at 15:41
  • I see nothing wrong with your code, you could simplify it like this: `chrome.runtime.sendMessage({text: web_adr}, callback)`. Please add details on what doesn't work. Also don't forget to declare items as `let` or `const` in loops, in your case `for (const imgElt of imgs)` – Guerric P Jun 17 '21 at 15:55
  • i just need to use the data inside the ```param1``` variable in for loop. but i could not get access the data. thanks for help @GuerricP – Kenan Baysal Jun 17 '21 at 19:21

0 Answers0