0

Duplicate of Display current URL in a chrome extension

The solution in my 'background.js':

$(document).ready(function(){
    chrome.tabs.query({'active': true, 'lastFocusedWindow': true, 'currentWindow': true}, function (tabs) {
    var url = tabs[0].url;
    console.log(url);
    alert(url)
    })
})

did not work for me. I also gave 'tabs' permission on manifest.json

{
    "manifest_version": 2,
    "name": "YtDl",
    "version": "0.1",
    "permissions": ["tabs"],
    "background": {
    "persistent": false,
    "scripts": ["jquery.min.js", "background.js"]
  },
    "content_scripts":[
        {
            "matches": ["<all_urls>"],
            "js": ["jquery.min.js", "content.js"],
        }
    ]
}

is there any other solution to get current tab url?

NOTE: I am trying to get URL from background script. when i reload the extension it works for one time in 'chrome://extensions/' and does not work at any other site.

iku
  • 133
  • 2
  • 9
  • Extensions have multiple parts so it depends on where you want that URL. – wOxxOm Apr 20 '20 at 15:30
  • I am trying to get URL from background script. when i reload the extension it works for one time at 'chrome://extensions/' and then it does not work at any other site. – iku Apr 20 '20 at 15:42
  • The background script is event-driven so you should put that code in an event listener. Currently your code runs when the background script runs (it happens on startup of the extension and when the background page is loaded) so it doesn't do anything useful. Alternatively, depending on what you want to do with that URL, you may not need the background script at all. – wOxxOm Apr 20 '20 at 15:48
  • `$(document).ready(function(){` in background.js does nothing useful at all, remove it, and use chrome.tabs.onUpdated or other suitable event, depending on what you want to do. And like I said, maybe you don't need the background script at all. – wOxxOm Apr 20 '20 at 15:58
  • Actually I want to do something in the page based on the url parameters whenever a page will load. – iku Apr 20 '20 at 16:27
  • Do you have any suggestion, how can I do it automatically @wOxxOm ? – iku Apr 20 '20 at 16:29
  • Scripts declared in content_scripts run automatically so you can use `location.search` in your content.js, no need for background script. – wOxxOm Apr 20 '20 at 16:31
  • Thank you @wOxxOm I have used `location.href` to get the URL in content script. – iku Apr 22 '20 at 15:42

0 Answers0