Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Bare minimum Chrome extension to inject a JS file into the given page when you click on the browser action icon. The script then inserts a new div into the DOM.
// this is the background code...
// listen for our browerAction to be clicked
chrome.browserAction.onClicked.addListener(function (tab) {
// for the current tab, inject the "inject.js" file & execute it
chrome.tabs.executeScript(tab.ib, {
file: 'inject.js'
});
});
// this is the code which will be injected into a given page...
(function() {
// just place a div at top right
var div = document.createElement('div');
div.style.position = 'fixed';
div.style.top = 0;
div.style.right = 0;
div.textContent = 'Injected!';
document.body.appendChild(div);
alert('inserted self... giggity');
})();
{
"name": "Injecta",
"version": "0.0.1",
"manifest_version": 2,
"description": "Injecting stuff",
"homepage_url": "http://danharper.me",
"background": {
"scripts": [
"background.js"
],
"persistent": true
},
"browser_action": {
"default_title": "Inject!"
},
"permissions": [
"https://*/*",
"http://*/*",
"tabs"
]
}
@ktmellow

This comment has been minimized.

Copy link

@ktmellow ktmellow commented Apr 20, 2016

You're a hero, Dan Harper!

@albinekb

This comment has been minimized.

Copy link

@albinekb albinekb commented Sep 14, 2016

AMAZING

@botmtl

This comment has been minimized.

Copy link

@botmtl botmtl commented Sep 27, 2016

Even better, this works with:

"permissions": [
    "activeTab"
  ]

... avoiding the dreaded "this script can read and change all your data on the websites you visit".

@Thatkookooguy

This comment has been minimized.

Copy link

@Thatkookooguy Thatkookooguy commented Sep 28, 2016

thanks for this! is it easy to make this work on specific urls without clicking the extension?

great work!

@danvine

This comment has been minimized.

Copy link

@danvine danvine commented Oct 13, 2016

@Thatkookooguy yes.
I'll leave this here in case anyone needs a heavier template. http://extensionizr.com/

@afd57

This comment has been minimized.

Copy link

@afd57 afd57 commented Oct 15, 2016

thanks for this. I have a problem. I want to take info at website. I changed this application.

background.js

chrome.browserAction.onClicked.addListener(function (tab) { // for the current tab, inject the "inject.js" file & execute it chrome.tabs.executeScript(tab.ib, {file: 'inject.js'}, function(result) { console.log(result[0]) } ); });

inject.js

(function() {
    var t3 = document.getElementById("time3");
        console.log(t3);//works;
        return t3;

})();

Function writes t3 on console. but don't return t3 variable. console.log(result[0]) writes 'null' ;

what is the problem this code ?

thaks good job

@dipongkor

This comment has been minimized.

Copy link

@dipongkor dipongkor commented Oct 28, 2016

Can I inject css any the same way?

@artursobon

This comment has been minimized.

Copy link

@artursobon artursobon commented Feb 7, 2017

background.js

chrome.tabs.executeScript(tab.ib, {

Shouldn't be there:

chrome.tabs.executeScript(tab.id, {

tab.id instead of tab.ib ?

In this case tab.ib is null, so:

The ID of the tab in which to run the script; defaults to the active tab of the current window.

https://developer.chrome.com/extensions/tabs#method-executeScript

@sinameraji

This comment has been minimized.

Copy link

@sinameraji sinameraji commented Jun 24, 2017

This is amazing ❤️

@shihokambara

This comment has been minimized.

Copy link

@shihokambara shihokambara commented Jul 9, 2017

thanks for this!
"persistent": false
also worked.

@Modelmat

This comment has been minimized.

Copy link

@Modelmat Modelmat commented Aug 16, 2017

This does not work....

@ghost

This comment has been minimized.

Copy link

@ghost ghost commented Aug 26, 2017

Great job!!

@Peru-J

This comment has been minimized.

Copy link

@Peru-J Peru-J commented Oct 23, 2017

Great job !!

can we execute jquery with this ? what changes i need to add to execute jquery script

@Shalinibunga2124

This comment has been minimized.

Copy link

@Shalinibunga2124 Shalinibunga2124 commented Oct 29, 2017

super and amazing.........................

@http91

This comment has been minimized.

Copy link

@http91 http91 commented Dec 1, 2017

Man, you saved my day.
Thanks!

@ORESoftware

This comment has been minimized.

Copy link

@ORESoftware ORESoftware commented Jan 1, 2018

is there a way to run/execute a Chrome Extension in a new tab/window by loading the extension's code in that new tab or window?
https://stackoverflow.com/questions/48048617/load-run-execute-chrome-extension-in-new-tab

@beherebaba

This comment has been minimized.

Copy link

@beherebaba beherebaba commented Jan 3, 2018

I wish I could kiss you :')

@alvarezgarcia

This comment has been minimized.

Copy link

@alvarezgarcia alvarezgarcia commented May 2, 2018

Never before this even tried a Chrome Extension.
Found this, check how to load on chrome.. in less than 30 seconds all working.

A real hero Darper!

@Iazzetta

This comment has been minimized.

Copy link

@Iazzetta Iazzetta commented Jun 7, 2018

THANK YOU!

@charusharma99

This comment has been minimized.

Copy link

@charusharma99 charusharma99 commented Jun 18, 2018

I want to insert bypass frame busting code into html. I donot know how to insert whole script.

<script type="text/javascript"> var prevent_bust = 0; window.onbeforeunload = function() { prevent_bust++; } setInterval(function() { if (prevent_bust > 0) { prevent_bust -= 2; window.top.location = 'http://www.example.com/'; } }, 1); prevent_bust = 0; window.onbeforeunload = function() { prevent_bust++; } setInterval(function() { if (prevent_bust > 0) { prevent_bust -= 2; window.top.location = 'frame_busted_page.html'; } }, 1); </script>

Thank you .

@sridharar

This comment has been minimized.

Copy link

@sridharar sridharar commented Jul 31, 2018

Danharper thanks for the idiomatic kit for getting things going.
Danvine thanks for the heavier template. Looks great and will try that.

I plunged into extension stuff, as I was getting tired of High Contrast Chrome extension not working, or only working sporadically.
Not sure why or what in my environment is making it not work. But I need something like that badly.

If you have any tips on how to make gmail display all its views/texts white on black background it would be a great head start for me.
That would be good for the start to be extended other pages as well.

Thanks in advance.

@zArubaru

This comment has been minimized.

Copy link

@zArubaru zArubaru commented Jul 31, 2018

@dipongkor
You can inject CSS with the insertCSS method. Though beware, you may experience some priority issues doing it this way.

For some use cases the previous is enough. For others my recommendation is to inject a script that injects the css that you need.

@frankhu-2021

This comment has been minimized.

Copy link

@frankhu-2021 frankhu-2021 commented Dec 10, 2018

This is truly so Convenient. Cheers and Thanks man!

@hanjin66

This comment has been minimized.

Copy link

@hanjin66 hanjin66 commented Feb 19, 2019

How do I click on a JavaScript pop-up on the page, that does not have an element ID

@arunganesan

This comment has been minimized.

Copy link

@arunganesan arunganesan commented Feb 23, 2019

Lifesavveerrrrrr

@brettsprad

This comment has been minimized.

Copy link

@brettsprad brettsprad commented Mar 11, 2019

is there a way to insert a linked JS file?
e.g. insert the file at this URL: testsite.com/files/script.js

@sam-aldis

This comment has been minimized.

Copy link

@sam-aldis sam-aldis commented Mar 26, 2019

https://codepen.io/sam-aldis/pen/NJJyax/

can you embed in comments? 😉
@dunklesToast

This comment has been minimized.

Copy link

@dunklesToast dunklesToast commented Apr 14, 2019

@brettsprad Yes you can. Just create a new script element, add it to the document and then set the src to your url

Something like this:

var s = document.createElement('script');
s.src = "http://link.to/js";
(document.head || document.documentElement).appendChild(s);
@art-n

This comment has been minimized.

Copy link

@art-n art-n commented May 28, 2019

<3<3

@wtorcaso

This comment has been minimized.

Copy link

@wtorcaso wtorcaso commented Jun 26, 2019

This is a newbie question: When I hear "Chrome Extension", I think of code that the user has to agree to run, and that can be removed by the user at any time. Is this like that, or is "extension" an overloaded word in this context, and means something else?

Thanks!

@antony

This comment has been minimized.

Copy link

@antony antony commented Jul 27, 2019

@wtorcaso you are correct in your assessment - a Chrome Extension is a user installable extension to the Chrome or Chromium browser.

@waqas-mehmood-pk

This comment has been minimized.

Copy link

@waqas-mehmood-pk waqas-mehmood-pk commented Sep 23, 2019

@dunklesToast I have tried your suggested method but failed to execute the script of injected file.
Here is what I have tried.

First Approach:

chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
    chrome.tabs.executeScript(tabs.id, {
         code: "document.body.appendChild(document.createElement('script')).src = 'https://test.com/js/site.com.js'";
    });
});

image

In this approach .js file injected but script of that file could not access/run.

Second Approach:

chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
    chrome.tabs.executeScript({file: "https://test.com/js/site.com.js"});
});

Third Approach:

chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
    chrome.tabs.executeScript({
       tabId: tabs.id,
       file: "https://test.com/js/site.com.js"
    });
});

In both 2nd and 3rd approaches file not injected.

@Veverke

This comment has been minimized.

Copy link

@Veverke Veverke commented May 6, 2020

According to the docs, if the goal is to inject scripts into tabs, I think declarative injection is the simplest solution. In the manifest, add

	"content_scripts": [
		{
		 "matches": ["https://*/*","http://*/*"],
		 "js": ["myJsFile.js"]
		}
	],

The above injects myJsFile.js into every tab opened in the browser.
And make sure you enabled 'activeTab' in the permissions setting.

@qtcoder999

This comment has been minimized.

Copy link

@qtcoder999 qtcoder999 commented Jun 5, 2020

you are awesome !!!!!!!! Thank you man!!!!

@AnthonyisMedia

This comment has been minimized.

Copy link

@AnthonyisMedia AnthonyisMedia commented Jun 17, 2020

How would you remove the div by clicking the extension icon?

This method has worked great for adding a fixed menu div on top of a webpage but it would be awesome if I could delete/remove what I added and reset the page to the way it was. All without refreshing the page of course.

I figured making these changes to the background script and adding an ID to my div for deletion would work but the code doesn't seem to find the div. So I can't remove the div I added.

`

// this is the background code...

var ToggleExtension = false;

// listen for our browerAction to be clicked

chrome.browserAction.onClicked.addListener(function (tab) {

// for the current tab, inject the "inject.js" file & execute it	
if (ToggleExtension == false){

   chrome.tabs.executeScript(tab.ib, { file: 'Inject.js' });
   ToggleExtension = true;

} else if (ToggleExtension == true){

   var MyDiv = document.getElementById(MyDiv);
   MyDiv.parentNode.removeChild(MyDiv);
   ToggleExtension = false;

}
});`
@ShamsherNawaz

This comment has been minimized.

Copy link

@ShamsherNawaz ShamsherNawaz commented Jul 9, 2020

Amazing..... Thanks man

File injected in any page when I click the icon. What if I want to inject file automaticaly after page load of a specific page/site.

@rrakso

This comment has been minimized.

Copy link

@rrakso rrakso commented Sep 9, 2020

Hi @ShamsherNawaz!
Look at this comment (here is the reference).

I added also to this solution this piece of code

window.addEventListener("load", () => {
  // Here the rest of the code executed when page is fully loaded
});
@bbsmithy

This comment has been minimized.

Copy link

@bbsmithy bbsmithy commented Oct 24, 2020

thanks for this! is it easy to make this work on specific urls without clicking the extension?

great work!

If you add this to your commands section in manifest.json

"commands":{
    "_execute_browser_action": {
      "suggested_key": {
        "default": "Ctrl+Shift+F",
        "mac": "MacCtrl+Shift+F"
      }
    }
  }

You can open the browser action with a keyboard command, which will trigger the onClick event

@Randomblock1

This comment has been minimized.

Copy link

@Randomblock1 Randomblock1 commented Jan 12, 2021

Thanks so much!! For anyone trying to inject JavaScript and run a function that already exists within the page:

inject.js

(function() {

        location.href="javascript:someExistingFunctionInPage(); void 0";

})();

from StackOverflow, because everything is

@ac-0rn

This comment has been minimized.

Copy link

@ac-0rn ac-0rn commented Jan 19, 2021

Exactly what I was looking for, thanks!

@Njerschow

This comment has been minimized.

Copy link

@Njerschow Njerschow commented Mar 3, 2021

This is exactly what I needed, thanks!

@theknightD2

This comment has been minimized.

Copy link

@theknightD2 theknightD2 commented Mar 16, 2021

I know people have already said this, but THIS IS EXACTLY WHAT I NEED! Thanks!

@tsikerdekis

This comment has been minimized.

Copy link

@tsikerdekis tsikerdekis commented May 8, 2021

Anyone knows if this solution works for V3?

@sidxd

This comment has been minimized.

Copy link

@sidxd sidxd commented May 23, 2021

Anyone knows if this solution works for V3?

You have to make a few changes:

browserAction -> action

tabs -> scripting (You need to change permissions in manifest.json too.)

file: 'inject.js' -> files: ['inject.js'] // should be array

You also need to add another required parameter called target where you add files.
target: { tabId: tabId // should be integer }

Checkout chrome's official migration checklist.

EDIT: Updated code

chrome.action.onClicked.addListener(function (tab) {

	// for the current tab, inject the "inject.js" file &amp; execute it	
       chrome.scripting.executeScript(tab.ib, {
                target: {tabId: tabId} // required in MV3
		files: ['inject.js']	
       });
});
@vineet-sinha

This comment has been minimized.

Copy link

@vineet-sinha vineet-sinha commented Jun 18, 2021

tab.ib is not a parameter, so the updated code should be:

chrome.action.onClicked.addListener(function (tab) {

	// for the current tab, inject the "inject.js" file &amp; execute it	
       chrome.scripting.executeScript({
                target: {tabId: tab.id},
		files: ['inject.js']	
       });
});
@asmirbelkic

This comment has been minimized.

Copy link

@asmirbelkic asmirbelkic commented Jul 21, 2021

any proper way to disable the extension then remove the injected content clicking the extension icon again ??
Ty guys

@600drive

This comment has been minimized.

Copy link

@600drive 600drive commented Aug 26, 2021

URL: testsite.com/files/script.js

chrome.browserAction.onClicked.addListener(function (tab) {
// for the current tab, inject the "www.site.com/system/trail/inject.js" file & execute it
chrome.tabs.executeScript(tab.ib, {
URL: www.site.com/system/trail/inject.js
//file: 'inject.js'
});
});

@600drive

This comment has been minimized.

Copy link

@600drive 600drive commented Aug 26, 2021

no work

@600drive

This comment has been minimized.

Copy link

@600drive 600drive commented Aug 26, 2021

According to the docs, if the goal is to inject scripts into tabs, I think declarative injection is the simplest solution. In the manifest, add

	"content_scripts": [
		{
		 "matches": ["https://*/*","http://*/*"],
		 "js": ["myJsFile.js"]
		}
	],

The above injects myJsFile.js into every tab opened in the browser.
And make sure you enabled 'activeTab' in the permissions setting.

myJsFile.js if i want store on domain how can i do ? thanks you for your reply

@caminhoperfeito

This comment has been minimized.

Copy link

@caminhoperfeito caminhoperfeito commented Sep 6, 2021

Thanks xD

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment