Tech C**P
15 subscribers
161 photos
9 videos
59 files
304 links
مدرس و برنامه نویس پایتون و لینوکس @alirezastack
Download Telegram
Now let's write the main JS code in order to add menu items into Chrome extension. Create background.js file in the same directory as manifest.json with the content below:

if (chrome && chrome.browserAction){
var baseUrl = "https://www.example.com"
chrome.runtime.onInstalled.addListener(function() {
chrome.tabs.create({ url: baseUrl + "/extension-installed/" });
});

chrome.runtime.setUninstallURL(baseUrl + "/extension-uninstalled/");

// open a new page on left clicking on the extension itself
chrome.browserAction.onClicked.addListener(function(activeTab) {
chrome.tabs.create({ url: baseUrl + "/my-home-page" });
});

chrome.contextMenus.create({
"id": "first_item",
"title": "This is the first item",
"contexts": ["browser_action"]
});

chrome.contextMenus.create({
"id": "second_item",
"title": "This is the second item",
"contexts": ["browser_action"]
});

chrome.contextMenus.onClicked.addListener(function(info)
{
urls = {
first_item: baseUrl + "/first-item",
second_item: baseUrl + "/second-item"
};
chrome.tabs.create({url: urls[info.menuItemId]});
});
}

There are many events that based on that event you can do an action. Let's review some of the codes above.

chrome.runtime.onInstalled.addListener: on extension installation open a url using chrome.tabs. As you recall from the previous post we have added tabs to the permission section of manifest.

chrome.runtime.setUninstallURL: open a url on extension uninstallation.

chrome.browserAction.onClicked.addListener: open a url when your extension in toolbar is clicked (at the right of the address bar).

chrome.contextMenus.create: create an item with specific id and title. contexts sections tells the browser to show the menu just when user right click on the extension in toolbar. You can add page to have the extension menu item on the main page of browser itself.

chrome.contextMenus.onClicked.addListener: When one of the menu items is clicked open the corresponding URL.

Now to test it go to chrome://extensions/. Make sure developer mode is enabled. Click on Load unpacked and select your extension folder and open it. It will be installed by now.

Enjoy working with Chrome Extension! :)

#chrome #xtension