How can I get the URL of the current tab from a Microsoft Edge extension

Tags: , ,



I’m experimenting with edge extensions , I’m trying to make one that reads the URL of the current tab, removes the string ‘%0A’ and then redirects to the cleaned URL, but I dont know how to read the current tab URL, I found how to do it in chrome:

 chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    // print object for debugging
    console.log(JSON.stringify(tabs[0]));
  
    // get active tab url
    var activeTab = tabs[0];
    var activeTabURL = activeTab.url;
    alert(activeTabURL)
  });

but It doesnt seem to work for Edge, I have the permission for ‘tabs’ set in my manifest. Hope you can help me out

Answer

I suggest you refer to an example below that may help you to get the URL of the current tab from the Edge browser extension.

manifest.json:

{
    "name": "Hello World",
    "version": "2.0.0",
    "description": "Simple Microsoft Edge Extension",
    "manifest_version": 2,
    "author": "abc",
    "icons": {
       "16": "icons/icon_16.png"
    },
    "browser_action": {
    "default_popup": "background.html",     
       
        "default_title": "Hello World"
    },
    "permissions": [
        "tabs",
        "<all_urls>"
    ],   
    "background": {
    "page": "background.html",
    "persistent": true
  },
    "content_scripts": [
    {
      "matches": ["http://*/*", "https://*/*"],
      "css" : ["light.css"],
      "js": ["js/content.js"],
      "run_at": "document_end"
    }
  ]
}

background.html:

<!DOCTYPE html>
<html>
<head>
    <title>demo</title>
    
</head>
<body>
    <div>
        <h3>Click the button to get the page URL...<h3><br>
        <button id="btn1">click me</button>
        <input type="text" id="txt1" style="width:300px">
    </div>
<script type="text/javascript" src="js/background.js"></script>
</body>
</html>

background.js:

var btn= document.getElementById("btn1");
btn.addEventListener("click", function(){
  abc();
});

function abc()
{
    chrome.tabs.query({active: true, lastFocusedWindow: true}, function(tabs) 
    {
            var tab = tabs[0];
            document.getElementById("txt1").value= tab.url;
            
    });
}

The extension file structure looks like below. You can create other files by yourself(like CSS files etc).

enter image description here

Test result with the MS Edge 89.0.774.45:

enter image description here

Further, you can try to modify the code of the extension as per your own requirements.

Thanks for your understanding.



Source: stackoverflow