Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

184
Vistas
Fetch weather api not working correctly for JS

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);
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

  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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda