0

I am developing a Chrome Extension where I take the current tabs url and give the countrycode as value for a dropdown. So far so good. My Problem is the JS is only executed, when I reopen the Popup.

My Flow is:

  1. reload the extension from chrome://extensions
  2. go a website, press ctrl + F5
  3. open the popup, nothing happens
  4. open the popup again, everything works fine

Popup.html is something like this:

<head>
    <link rel="stylesheet" href="stylesheet.css">
</head>
<body>
        <select id="dropdown"></select>
    <script src="Popup.js"></script>
</body>
</html>

Popup.js is like this:

 const getCurrentUrl = () => {
chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
    var currentTab = tabs[0].url;
    localStorage.setItem("currentUrl",currentTab);
})
    const setSelected = () => {
        let select = document.getElementById("dropdown");
        let result = localStorage.getItem("currentUrl");
        select.value=result;
    }
    window.onload = function () {
        getCurrentUrl();
        setSelected();
}

short version of Manifest:

{    
  "version": "0.1.0",
  "manifest_version": 2,
  "browser_action": {
    "default_popup": "popup.html",
    "default_icon": "favicon.ico",
    "default_script": "Popup.js"
  },

  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "permissions": [
    "tabs",
    "activeTab",
    "storage"
  ],
  "commands": {
    "_execute_browser_action": {
      "suggested_key": {
        "default": "Alt+S",
        "mac": "MacCtrl+Shift+F"
      },
      "description": "Opens popup.html"
    }
  }
}
Mixdy
  • 13
  • 5

1 Answers1

0

This is essentially a duplicate of Why is my variable unaltered after I modify it inside of a function?

You should use the results of an asynchronous API inside the callback.

Here's the entire popup.js:

chrome.tabs.query({active: true, currentWindow: true}, ([tab]) => {
  document.getElementById('dropdown').value = tab.url;
});

This code assumes popup.html loads popup.js at the end (just like you do currently):

  <script src=popup.js></script>
</body>
wOxxOm
  • 65,848
  • 11
  • 132
  • 136