Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

183
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda