When you will be able to insert some HTML code into a web page, then you can change or enhance the way a website behave. Also as a developer, you can provide your users those missing features, which they always look for in some website.

For this, one can write a Javascript code. But how this code will be injected into the target page source?

This post will guide you how to create a chrome extension that will handle the injection of our Javascript code into Gmail page. If you want to know the basics of creating extensions for chrome, you can read our post regarding Chrome Extension Tutorial to Display RSS Blog Feeds.


Download code from the link given below

inject javscript in a page using chrome extension


For excellent service in Email marketing, Bulk mailing, Email list management and many more, you must take a look at MailGet.

Chrome extensions provide a way out to execute our own script into a web page via “content-script”. Take a look at the following code snippet from manifest file,

"content_scripts": [
{ "run_at" :"document_end",
"matches": ["https://mail.google.com/*"],
"js": ["jquery-1.11.3.min.js","script.js"],
"css":["css/mycss.css"] }
],

Here “jquery-1.11.3.min.js”, “script.js” , “mycss.css” are the files I have defined as my content script.

You might already know that chrome browser requires a “manifest.json” file in the extension’s directory. You define a single file or a bundle of more than one file, to inject as your content script in the extension’s manifest file.

We will proceed with the following steps to complete our task. In the extension’s root directory,
1.) Create a file with name “manifest.json” put inside the code given later.
2.) Create a Javascript file “script.js” which upon execution insert HTML into Gmail page.
3.) Place the applied styles to the injected HTML into a separate file “mystyle.css” and place it into CSS folder.
4.) Use of chrome.extension.getURL(“img/MailGet.png”) will give the absolute path of the file Mailget.png.


Prepare the manifest

The content of file are self-suggesting and comments are also provided to have you a clear idea about the usage.
In the content script section, there are some additional properties such as “run_at” tells extension when to execute our script with options of “document_start”, “document_end” and “document_idle” and if you intend the script to execute only for some specific page then “matches” specifies the pattern of the url to match in the address bar.

Note: Don’t forget to delete all the comments in menifest file before you use the code.

manifest.json

{
"manifest_version": 2,
//current manifest version by chrome

"name": "Gmail inject pop-up",
"description": "This extension will append an icon in the gmail homepage and a pop-up will appear on click over that icon.",
"version": "1.0",
//Name,Description & version of your extension

"content_scripts": [    <-------------------------------------------------------------Content Script details in manifest
{ "run_at" :"document_end",
"matches": ["https://mail.google.com/*"],
"js": ["jquery-1.11.3.min.js","script.js"],
"css":["css/mycss.css"]
} ],
//"run_at" tells when to load the javascript,
//"matches" tells the URL to match to inject the code which I'm using Gmail here,
//"js" tells all .js files to inject,
//"CSS" tells about all included CSS files for injection.

"web_accessible_resources":["img/*.png"]
}
//web_accessible_resources specify the path and format of files which the web page require to load from extension.
//But why? because webpage and extension executes in isolated environments.They can't access one another's resources directly.
//and in the following way we allow web page to access the required files from extension.

Content script files

script.js

Following script instructs the extension to inject a “clickable icon with HTML pop-up” code into gmail page.

$(document).ready(function() {   // Load the function after DOM ready.

var link1=chrome.extension.getURL("img/MailGet.png");     //Get absolute path of the file residing your extension.
var t1='<div id="pop"><a href=""><img id="mgt" src="'+link1+'"width="25" height="24"></a></div>'    //now set the src to absolute path.
$(".gb_Lb").prepend(t1);     //Insert MailGet icon into top-right corner of Gmail home.

var link2=chrome.extension.getURL("img/button_cancel.png");
var link3=chrome.extension.getURL("img/AoRankLogo.png");
var t2='<div id="pop_bg" style="height: 100%; width: 100%;"></div><div id="mgt_popup"><span class="popup_close"></span><div><img id="logo" src="'+link3+'"/></div><div id="pop_inner"><label id="user"></label><input type="button" id="mailgett" value="Go To MailGet"/></div></div>'
$("body").append(t2);

$("#pop").click(function() {//click on injected mailget icon.
event.preventDefault();//first stop default behaviour of anchor.
$("#pop_bg").css("display", "block");//Show pop-up background.
$("#mgt_popup").css("display", "block");//Show pop-up div.
//Inject dynamically generated html from here( However i've used a string only).
$("#user").html("MailGet is an online Email Management Service which allow you to Send Bulk and Drip Emails<br><br>");
});

$(".popup_close").click(function(){//click close symbol hides popup
$("#pop_bg").css("display", "none");
$("#mgt_popup").css("display", "none");
});

$("#mailgett").click(function() { // click on "Go To Mailget" button hides popup and opens provided url in new tab.
$("#pop_bg").css("display", "none");
$("#mgt_popup").css("display", "none");
window.open("https://www.formget.com/mailget/" , '_blank');
});
});

mycss.css

The extension itself injects the following CSS styles into the target page if the file is correctly specified in manifest.json

@import url(https://fonts.googleapis.com/css?family=Raleway);

img#mgt{
border-radius:10px;
}
div#pop_bg{
opacity:0.6;
background: #000;
left: 0;
position: absolute;
top: 0;
z-index: 500;
display:none;
height: 100%;
width: 100%;
}
div#mgt_popup{
background: #FFF;
height:330px;
width:500px;
z-index:550;
display:none;
left: 42%;
top: 52%;
margin-left:-110px;
margin-top:-228px;
position: absolute;
border: 5px solid rgba(58, 53, 40, 0.46);
}
.popup_close{
background:url("https://cdn0.iconfinder.com/data/icons/slim-square-icons-basics/100/basics-22-48.png") no-repeat;
height: 48px;
width: 48px;
position: absolute;
top: -9px;
left: 461px;
opacity: 0.5;
cursor:pointer;
}
input[type=button]{
margin: 27px 0px 0px -52px;
color: #fff;
background-color: #FFBC00;
border-color: #FFBC00;
padding: 12px 130px;
border:1px solid white;
font-family:raleway !important;
font-Weight:bold;
font-size:18px;
color:white;
}
div#pop{
width: auto;
height: auto;
padding-left: 17px;
padding-top: 2px;
}
#pop_mail_read{
margin: 75px 0 0 184px;
}
img#logo{
margin: 37px 8px 26px 33%;
}
div#pop_inner{
margin: 0 22%;
text-align: center;
}

Download Jquery file and place it in the application folder.Make sure the file-name is correct in manifest file.

 


Load the Extension

Follow these steps:
1.) Go to “Menu<<More Tools<<Extensions”  OR type in the address bar “chrome://extension”.
2.) Check the “developer mode” option to enable loading the extension.
3.)Click “Load unpacked extension” then select the application folder(not zipped).
The extension is now loaded in chrome to execute.

Open Gmail in the browser and you will see the MailGet icon MailGet in the Top-Right corner of the page.This is the icon we injected right away through our content-script specifically script.js file.

Now click on that icon and a popup will appear.This is the same popup we have injected as HTML.


Conclusion

  • We created a chrome extension which executes our javascript(script.js) inside a web page.
  • We specified the web page as “gmail.com” otherwise one can also make the script work in more than one or all pages and tabs.
  • The CSS we have created for our HTML will automatically get applied if the path in the manifest is correct.
  • Chrome runs our script when there is URL in the address bar matching to gmail’s.

Further, you can also extend the script to handle communication with external resources.

I hope that now the concept of injecting code in a web page would be clear to you. Play with the code and please let us know if you find any trouble. Keep visiting our site for many more useful blogs.Thanks for reading!!!