Chrome Extension – Redirect to base URL

HOW TO MAKE SIMPLE CHROME EXTENSION

Chrome Extension – Redirect to base URL

Posted by Rahul Dhokia | July 17, 2017
Ext

If you’re wondering how to make a Chrome Extension, Chrome has wonderful documentation for basic implementations. But for use extra level features requires a lot of Google and forums.

Today, lets make an simple Chrome extension that interacts with the page: it will find the base external link on the page and open it in a new tab.
We will need just 4 files.
1) manifest.json
2) content.js
3) background.js
4) Icon
Create a folder named “ChromeExt” (You can add whatever you want)
Create manifest.json
– This file tells Chrome important information about your extension, like its name and info.
– See example below.

{
"manifest_version": 2,
"name": "iTreeni - Base URL",
"version": "0.1",
"description": "Find a base URL of the current page and redirect to it.",
"author": "iTreeni"
}

The manifest_version should always be 2, because version 1 is deprecated from January 2014. So far our extension does absolutely nothing, but let’s load it into Chrome anyway.

Lets Load our extension into browser

For load our extension in Chrome, open up chrome://extensions/ in your browser and check “Developer mode” on top right. Now click “Load unpacked extension…” and select the extension’s folder. You should now see your extension in the list.

When you change or add code in your extension, just come back to this page and reload the page. Chrome will reload your extension.

Content.js

A content script is simple JavaScript file that runs in the context of web pages. This means that a content script can interact with web pages that the browser visits.

Let’s create a new file named content.js

console.log("My First Chrome Extension");

To inject the script, we need to tell our manifest.json file about it.

"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": ["content.js"]
}
]

Reload your Chrome extension. Every single page you visit now you can see console of it.

Base URL

We require jQuery for it. You can download it and add it in manifest.json.

"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": ["jquery-3.2.1.min.js", "content.js"]
}
]

Now that we have jQuery, let’s use it to find base URL. add below code in content.js

var baseURL = $("a[href^='http']").eq(0).attr("href");
console.log(baseURL);

Try it out – you should see the output in your console on every page you visit.

Browser Actions

Add the icon.png in manifest.json:

"browser_action": {
"default_icon": "icon.png"
}

In order to use the browser action, we need to add message passing.

Message passing

Add below code in manifest.json about the background script:

"background": {
"scripts": ["background.js"]
}

Now we’ll add background.js:

chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
var activeTab = tabs[0];
chrome.tabs.sendMessage(activeTab.id, {"message": "clicked_browser_action"});
});
});

This sends an arbitrary JSON payload to the current tab. The keys of the JSON payload can be anything, but I chose “message” for simplicity. Now we need to listen for that message in content.js:

chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if( request.message === "clicked_browser_action" ) {
var baseURL = $("a[href^='http']").eq(0).attr("href");
console.log(baseURL);
}
}
);

Notice that all of our previous code has been moved into the listener, so that it is only run when the payload is received. Every time you click the browser action icon, you should see a URL get logged to the console. If it’s not working, try reloading the extension and then reloading the page.

Now reload your extension and check console.

Opening in new tab

We can use the chrome.tabs API to open a new tab:

chrome.tabs.create({"url": "http://google.com"});

But chrome.tabs, we can use only in background.js. Lets create some logic.
– Listen for a click on the browser action in background.js. When it’s clicked, send a clicked_browser_action event to content.js.
– When content.js receives the event, it grabs the URL of the first link on the page. Then it sends open_new_tab back to background.js with the URL to open.
– background.js listens for open_new_tab and opens a new tab with the given URL when it receives the message.

Clicking on the browser action will trigger background.js, which will send a message to content.js, which will send a URL back to background.js, which will open a new tab with the given URL.

First, we need to tell content.js to send the URL to background.js. Change content.js to use below code:

chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if( request.message === "clicked_browser_action" ) {
var baseURL = $("a[href^='http']").eq(0).attr("href");
chrome.runtime.sendMessage({"message": "open_new_tab", "url": baseURL});
}
}
);

Now we need to add some code to tell background.js to listen for that event:

chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
var activeTab = tabs[0];
chrome.tabs.sendMessage(activeTab.id, {"message": "clicked_browser_action"});
});
});

chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if( request.message === "open_new_tab" ) {
chrome.tabs.create({"url": request.url});
}
}
);

Now when you click on the browser action icon, it opens a new tab with the first external URL on the page.

All Code will look like.

manifest.json

{
 "manifest_version": 2,
 "name": "iTreeni - Base URL",
 "version": "0.1",
 "description": "Find a base URL of the current page and redirect to it.",
 "author": "iTreeni",
 "content_scripts": [
 {
 "matches": ["<all_urls>"],
 "js": ["jquery-3.2.1.min.js", "content.js"]
 }
 ],
 "browser_action": {
 "default_icon": "icon.png"
 },
 "background": {
 "scripts": ["background.js"]
 }
}

background.js

chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
var activeTab = tabs[0];
chrome.tabs.sendMessage(activeTab.id, {"message": "clicked_browser_action"});
});
});

chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if( request.message === "open_new_tab" ) {
chrome.tabs.create({"url": request.url});
}
}
);

content.js

chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if( request.message === "clicked_browser_action" ) {
var baseURL = $("a[href^='http']").eq(0).attr("href");
chrome.runtime.sendMessage({"message": "open_new_tab", "url": baseURL});
}
}
);

Add a comment

*Please complete all fields correctly

Related Blogs

Posted by Rukmi Patel | December 2, 2019
iTreeni Technolabs Outshines at GoodFirms by Providing End-To-End Business Solutions
Empowering clients' business by leveraging technology-enabled solutions endows iTreeni Technolabs to tap into the list of top web development companies in Australia at GoodFirms. View iTreeni Technolabs' GoodFirms' profile to...
MEAN-Vs-Full-stack
Posted by Rukmi Patel | April 9, 2019
Comparing Full Stack V/S MEAN Stack approach
The web and mobile app development services have stepped up to next level in last 5 years. Web and apps are all built utilizing a ‘stack’ of various technologies like...
Posted by Rukmi Patel | September 6, 2018
Headless Drupal or DeCoupled Drupal
Now a days, front-end technologies like Angular, React.js, Backbone.js etc have started attracting audience because of its advantages over traditional rendering approach. Server side frameworks like Laravel, Node.js have already...