- Create javascript file with code to inject.
- Add to accessible resources in manifest.json:
"web_accessible_resources": [
{
"resources": [<javascript file path>],
"matches": [...]
}
],
- 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()
}
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) {
...
})
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.