1

I'm developing Chrome Extension and I want to get weather info with fetch() but When I save the incoming data named weatherData in my own variable named weatherData, it becomes undefined. That's why the codes are not working correctly. Please help.

API Key is true because console.log(data) is working well but console.log(weatherData) is not working.

This content script:

const hostname = window.location.hostname;

if(hostname.includes("google.com")) {
    var weatherData;

    document.body.innerHTML += 
    "<span id='content_weather'>"+
    "<span id='weather_temp'></span>"+
    "</span>";
    getWeather();
    setWeather();
}

function getWeather() {
    fetch("https://api.openweathermap.org/data/2.5/weather?lat=39.106141&lon=39.548280&appid={MY API KEY}&units=metric&lang=tr")
    .then(response => response.json())
    .then(data => weatherData = data);
}
function setWeather() {
    document.getElementById("weather_temp").innerHTML = JSON.stringify(weatherData.main.temp);
}
Ekin
  • 107
  • 1
  • 9

1 Answers1

1
  1. fetch is asynchronous so the actual network request is performed after the current execution stack fully completes, meaning that setWeather runs too early. The solution is to call setWeather inside the last then() or use the async+await syntax.

  2. Never assign to innerHTML/outerHTML of a site's body because it recreates the entire DOM and thus destroys all event listeners attached by the site programmatically, breaking its behavior/UI. The solution is to use insertAdjacentHTML or construct DOM nodes explicitly.

Here's how your entire code might look:

if (location.hostname === 'www.google.com') {
  fetch('https://api.......').then(r => r.json()).then(data => {
    const t = JSON.stringify(data.main.temp);
    document.body.insertAdjacentHTML('beforeend',
      `<span id='content_weather'><span id='weather_temp'>${t}</span></span>`);
  });
}

This may fail in modern Chrome because it blocks cross-origin requests in content scripts, so you might need to use the background script as shown in this answer.

wOxxOm
  • 65,848
  • 11
  • 132
  • 136