Content Script — Google Chrome Extension

Deepak Rai
2 min readOct 13, 2021

What is Content Script

Content scripts are files that run in the context of web pages. By using the standard Document Object Model (DOM), they are able to read details of the web pages the browser visits, make changes to them, and pass information to their parent extension.

Usage of Content Script

Lets suppose you have a webpage with following html content

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>

<h1>This is a Heading</h1>
<p id=”testPara”>This is a paragraph.</p>

</body>
</html>

Now If you want to modify the content of web page using content script, you can have below scripts

var p = document.getElementById(“testPara”);
p.inner_html = “test para1”;
p.addEventListener(“click”, () =>
alert(‘test click’)
, false);

Content scripts can be declared statically or programmatically injected.I am going to explain how you can inject it statically. Below is the content of menifest.json file

{
“name”: “Test”,
“version”: “1.0”,
“permissions”: [
“tabs”
],
“description”: “Test”,
“background”: {
“persistent”: false,
“scripts”: [
“jquery.js”,”background.js”
]
},
“content_scripts”: [
{
“matches”: [
“*://*/*”
],
“js”: [“jquery.js”,”content_dip.js”],
“run_at”: “document_end”,
“all_frames”: true
}
],
“browser_action”: {
“title”: “Test”
},
“manifest_version”: 2
}

We have injected two files under content scripts i.e. juqery.js and content_dip.js. Below is the content of content_dip.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
$(“input._17N0em”)[0].click();
$(“input._17N0em”).val(‘8467817933’)

});

We are trying to find input box in a page and triggering click event on it and after that trying to change the value of the input box. Get the sample files for this using below link

https://github.com/deepuRai/chrome_extension_content_script

Please upload this extension and once it is active, please click on extension link to trigger your changes under content_dip.js. Just to see whether your files has been added to your page content scripts, please open developer tools in chrome and go to Content Scripts under source tab. Please see below screenshot for your reference

--

--