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