Skip to content

Instantly share code, notes, and snippets.

@yardenlaif
Created August 30, 2023 16:17
Show Gist options
  • Save yardenlaif/312180106dc3641b79eac3361a7c95db to your computer and use it in GitHub Desktop.
Save yardenlaif/312180106dc3641b79eac3361a7c95db to your computer and use it in GitHub Desktop.
Injecting Javascript in Chrome Extension
  1. Create javascript file with code to inject.
  2. Add to accessible resources in manifest.json:
  "web_accessible_resources": [
    {
      "resources": [<javascript file path>],
      "matches": [...]
    }
  ],
  1. In your content script, load the javascript:
var s = document.createElement('script')
s.src = chrome.runtime.getURL(<javascript file path>)
;(document.head || document.documentElement).appendChild(s)
s.onload = function () {
  s.remove()
}

To communicate with content script

Use DOM event listeners to communicate. To send an event from injected script (this example will send once the document is loaded):

setTimeout(function () {
  document.dispatchEvent(
    new CustomEvent('event-name', {
      detail: <object to send>,
    })
  )
}, 0)

Add a listener in the content script:

document.addEventListener('event-name', function (e) {
  ...
})

Use Cases

This can be used to access global variables from the webpage, to make certain functions available to html elements, to send network requests and more.

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