How to get current URL in Chrome on click of the button

后端 未结 2 946
你的背包
你的背包 2021-01-14 16:48

I am making an chrome extension that shares url to one website. Now I need a code that can get current URL navigated in browser. When I click on icon I want to open new tab

相关标签:
2条回答
  • 2021-01-14 17:25

    You can use following function

    chrome.tabs.getSelected(null,function(tab) {
        var taburl = tab.url;
    });
    
    0 讨论(0)
  • 2021-01-14 17:28

    When the chrome.browserAction.onClicked event is dispatched, the first argument holds information about the current tab.

    To get the URL of the current tab, first request the activeTab permission in the manifest file (the tabs permission is unnecessary, you can omit it). Then, getting the URL is as simple as reading tab.url:

    chrome.browserAction.onClicked.addListener(function(tab) {
        var url_encoded_url = encodeURIComponent(tab.url);
        var newURL = "http://www.leegly.com/sharer.php?u=" + url_encoded_url;
        chrome.tabs.create({ url: newURL });
    });
    

    Note that I've used encodeURIComponent. Without this, your code will fail if the current URL contains an ampersand (&).

    0 讨论(0)
提交回复
热议问题