8

I'm creating my first Chrome extension and I need some help. I I think everything is working except the fact that I can't get the current URL of the tab.

var menu = chrome.contextMenus.create({
    "title": "extension",
    "contexts": ["all"]
  });

chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
        var siteUrl = tabs[0].url;
});

chrome.contextMenus.onClicked.addListener(function(activeTab)
{

    chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
        var siteUrl = tabs[0].url;
    });

    var finalUrl = "http://example.com/";

    finalUrl += encodeURI(siteUrl);

    // Open the page up.
    chrome.tabs.create(
        {
            "url" : finalUrl
        }
    );
});

Can anyone please help me? Thanks.

EDIT:

Thank you for your replies. I got it working by moving

var finalUrl = "http://example.com/";

    finalUrl += encodeURI(siteUrl);

    // Open the page up.
    chrome.tabs.create(
        {
            "url" : finalUrl
        }

Inside

chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
        var siteUrl = tabs[0].url;
    });
Makyen
  • 31,849
  • 12
  • 86
  • 121
xKripz
  • 103
  • 1
  • 1
  • 4
  • 1
    Does `document.location.href` not work? – megawac Jan 12 '14 at 19:27
  • 1
    @megawac No, that will retrieve chrome-extension://bjbdnjemkpaehlbckilllpakbphkkfme/src/bg/background.html – xKripz Jan 12 '14 at 19:40
  • 2
    Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Teepeemm Oct 05 '15 at 21:33
  • The code in the question and subsequent edit by the OP make it clear that the issue in the OP's implementation was a duplicate of the Async code ref question linked in the comment above. However, the accepted answer provides a solution to the situation that is sufficiently better such that I don't feel this question should be closed as a duplicate. In other words, this question is an [XY problem](https://www.google.com/search?as_q=XY+problem). The OP's implementation has the dup issue, but the best solution is to solve the actual situation, not to fix the OP's implementation. – Makyen Nov 29 '16 at 21:33

4 Answers4

17
chrome.tabs.getCurrent(function(tab){
    alert(tab.url);
});

OR if you're in a content script,

alert(document.location.href);
David Dehghan
  • 22,159
  • 10
  • 107
  • 95
Mike M
  • 752
  • 1
  • 5
  • 13
8

If you are using content script you can use

document.location.href

document.location is Object and can provide set of useful chunks in the URL

  • document.location.host returns domain name ex: "http://www.google.com/"
  • document.location.path returns the part after the domain name
  • document.location.hash returns whatever after # symbol in the url
Ahmed Gaber
  • 188
  • 2
  • 5
7

The info you require are provided to you already in the callback of the onClicked listener.

chrome.contextMenus.onClicked.addListener(function(info, tab) {
    // The URL of the tab (if any)
    var tabURL = tab && tab.url;

    // The URL of the page (if the menu wasn't triggered in a frame)
    var pageURL = info.pageUrl;

    // The URL of the frame (if the menu was triggered in a frame)
    var frameURL = info.frameUrl;

E.g. you could achieve what you want like this:

manifest.json:

{
    "manifest_version": 2,
    "name":    "Test Extension",
    "version": "0.0",

    "background": {
        "persistent": false,
        "scripts": ["background.js"]
    },

    "permissions": ["contextMenus"]
}

background.js:

var baseURL = 'http://example.com/';

chrome.contextMenus.create({
    id: 'myMenu',   // <-- event-pages require an ID
    title: 'Do cool stuff',
    contexts: ['all']
}, function () {
    /* It is always a good idea to look for errors */
    if (chrome.runtime.lastError) {
        alert('ERROR: ' + chrome.runtime.lastError.message);
    }
});

chrome.contextMenus.onClicked.addListener(function(info, tab) {
    /* Check which context-menu was triggered */
    if (info.menuItemId === 'myMenu') {
        /* Get the URL of the frame or (if none) the page */
        var currentURL = info.frameUrl || info.pageUrl;

        /* Open a new tab */
        chrome.tabs.create({
            url: baseURL + encodeURI(currentURL)
        });
    }
});
gkalpak
  • 47,844
  • 8
  • 105
  • 118
  • You've got a little bit of duplication in your first code block: `info.pageUrl && info.pageUrl;` should be `info.pageUrl;` (likewise for `frameUrl`. +1 for the correct way of approaching the problem though! – Rob W Jan 12 '14 at 20:50
  • thank you so much, ive spent ages on this assuming it was the tab api – random-forest-cat Nov 16 '14 at 19:40
1

Function:

function getCurrentUrl(callBackFuntion){
//you are in content scripts
    if(null == chrome.tabs || null == chrome.tabs.query){
        callBackFuntion(document.location.href);
    }else{
//you are in popup
        var queryInfo = {
            active: true, 
            currentWindow: true
        };
        chrome.tabs.query(queryInfo, function(tabs) {
            var tab = tabs[0]; 
            callBackFuntion(tab.url);
        }); 
    }
}

Function call:

function alertUrl(url){
    console.log("currentUrl : " + url);
}
getCurrentUrl(alertUrl);
Siddarth Kanted
  • 5,738
  • 1
  • 29
  • 20