xKripz xKripz - 4 days ago 6
Javascript Question

Get current URL from within a chrome.contextMenus.onClicked listener

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;
});

Answer

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)
        });
    }
});
Comments