Skip to content

Instantly share code, notes, and snippets.

@danharper
Last active May 22, 2024 11:09
Show Gist options
  • Save danharper/8364399 to your computer and use it in GitHub Desktop.
Save danharper/8364399 to your computer and use it in GitHub Desktop.
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"
]
}
@Suraj-bhan
Copy link

hey
@danharper I want to inject some elements on page load(when some specific element is loaded on the page) in some particular webpage in some specific container without clicking the extension icon, is there any way I can do that?

@arthurbolsoni
Copy link

arthurbolsoni commented Oct 6, 2022

hey @danharper I want to inject some elements on page load(when some specific element is loaded on the page) in some particular webpage in some specific container without clicking the extension icon, is there any way I can do that?

i trying doing it with chrome.scripting.executeScript but until now i have doing this way:

manifest v3

  "content_scripts": [
      {
          "matches": [
              "https://*.twitch.tv/*"
          ],
          "run_at": "document_start",
          "js": [
              "content-script.js"
          ]
      }
  ],
  "web_accessible_resources": [
      {
          "resources": [
              "app/bundle.js"
          ],
          "matches": [
              "<all_urls>"
          ]
      }
  ]

content-script.js

function init(items) {
  var s = document.createElement("script");
  s.src = chrome.runtime.getURL("app/bundle.js");
  s.onload = function () {
    this.remove();
  };

  (document.head || document.documentElement).appendChild(s);

  window.addEventListener("message", (event) => {
    if (event.data.type && event.data.type == "init") {
      window.postMessage(
        {
          type: "setInit",
          value: chrome.runtime.getURL("app"),
        },
        "*",
      );
    }
    if (event.data.type && event.data.type == "getSetting") {
      window.postMessage(
        {
          type: "setSetting",
          value: items,
        },
        "*",
      );
    }
  });
}

chrome.storage.local.get(["whiteList", "toggleProxy", "proxyUrl"], (items) => init(items));

so, the bundle is loaded when the page is opened

i think is posible do it with less lines using chrome.scripting

@murat1999
Copy link

I have a question regarding that. I know how to inject a js file when some action is triggered, but how can I inject a certain function in the js file? Like in the above example we are injecting js/inject.js file but I want to inject or execute a certain function in the background.js from js/inject.js file when I click the button in the popup.

@arthurbolsoni
Copy link

arthurbolsoni commented Dec 15, 2022

you will execute all the file as a function.

( () => {

//code

})()

I wasted a lot of time trying to find a way to pass parameter to this file. until you find the events.

You can run the file and tell it which function to activate using events: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

@murat1999
Copy link

murat1999 commented Dec 15, 2022

you will execute all the file as a function.

( () => {

//code

})()

I wasted a lot of time trying to find a way to pass parameter to this file. until you find the events.

You can run the file and tell it which function to activate using events: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

My goal is to run certain function say in js/inject.js file in all tabs in my chrome. Does by iterating all tabs and executing this js file on each tab give me a correct result? And when I run and tell which function to activate using events does it run on each tab individually?
My function is retrieving DOM, and other tab info (user agent, cookies etc) from each tab. And I am wondering if it works for each tab when I run js/inject.js file

@Jumpjetjumpjet
Copy link

Jumpjetjumpjet commented Jan 19, 2023

Hi Good day
I have a plugin whose manifest version is 2 and I updated it to 3 and I don't know if it is correct or not but it gives an error in the background that the document is not defined.
My plugin files:
manifest.json
background.js
pics.png
content.js
I will put the code

//manifest.json v2
{
"manifest_version": 2,
"name": "bot",
"version": "5.07",
"description":"Telegeram : @ali_barati86",
"content_scripts" : [{
"matches" : ["http:///","https:///"],
"js" : ["background.js"]
}],

"browser_action": {
"default_icon": "crash.png",
"default_title": "Crash Bot"
},
"web_accessible_resources": ["content.js"],
"permissions": [
"https:///",
"http:///",
"tabs"
]
}

I updated the above codes to version three
//manifest.json v3

{
"manifest_version": 3,
"name": "bot",
"version": "5.07",
"description":"Telegeram : @ali_barati86",
"permissions" : [
"activeTab",
"scripting",
"tabs"
],

"host_permissions": [
"http:///",
"https:///",
"<all_urls>"
],
"background": {
"service_worker": "background.js",
"type": "module"
},
"icons":{
"16": "crash.png",
"32": "crash.png",
"48": "crash.png",
"128": "crash.png"
},
"action": {
"default_title": "crash bot",
"default_icon": "crash.png"
},
"web_accessible_resources": [
{
"resources": [
"content.js"
],
"content_security_policy": {
"extension_pages": "script-src 'self'; object-src 'self'",
"sandbox": "sandbox allow-scripts; script-src 'self' 'https://apis.google.com/' 'https://www.gstatic.com/' 'https://.firebaseio.com' 'https://www.googleapis.com' 'https://ajax.googleapis.com'; object-src 'self'"
},
"matches": [
"http://
/",
"https://
/*",
"<all_urls>"
]
}
]
}

//background.js

var s = document.createElement('script');
s.src = chrome.extension.getURL("content.js");
s.onload = function() {
    this.parentNode.removeChild(this);
};

(document.head||document.documentElement).appendChild(s);


Please help me, I'm waiting, send me an email or a telegram
baratiali116@gmail.com
Telegram: @ali_barati86
If you want to tell me to check the plugin, please solve my problem, thank you
Plugin download link:
https://uupload.ir/view/extension_lst.zip/

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