Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

182
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!