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

ⅰ亾dé卋堺 提交于 2020-01-21 08:54:05

问题


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 (http://www.thatsite.com/sharer.php?u= + current URL).

I have two files:

manifest.json

{
    "name": "Share on that site",
    "version": "1",
    "browser_action": {
        "default_icon": "icon.png"
    },
    "background": {
        "scripts": ["background.js"]
    },
    "permissions": ["tabs"],
    "manifest_version": 2
}

and background.js

chrome.browserAction.onClicked.addListener(function(activeTab){
    var newURL = "http://www.leegly.com/sharer.php?u=" + <current URL here>;
    chrome.tabs.create({ url: newURL });
});

回答1:


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 (&).




回答2:


You can use following function

chrome.tabs.getSelected(null,function(tab) {
    var taburl = tab.url;
});


来源:https://stackoverflow.com/questions/17379190/how-to-get-current-url-in-chrome-on-click-of-the-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!