Skip to content

Instantly share code, notes, and snippets.

@dotproto
Created June 13, 2019 17:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dotproto/aa441015ba32e9280c0a838d75d04897 to your computer and use it in GitHub Desktop.
Save dotproto/aa441015ba32e9280c0a838d75d04897 to your computer and use it in GitHub Desktop.
Simple extension that injects a script before the page loads
console.log('content script – start body');
function injectScript(parent) {
console.log('injected script - start body')
const script = document.createElement('script');
script.textContent = `console.log('injected script'); window.GlobalClass = function() {};`;
parent.appendChild(script);
}
// Options for the observer (which mutations to observe)
var config = { attributes: false, childList: true, subtree: false };
// Callback function to execute when mutations are observed
var callback = function(mutationsList, observer) {
var targetNodeFound = false;
for(var mutation of mutationsList) {
console.log('A child node has been added or removed.', mutation);
for (var node of mutation.addedNodes) {
if (node.nodeName === 'HEAD') {
injectScript(node);
}
}
}
};
// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(document.documentElement, config);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
This is a test
<script>
console.log('inline page script - start body');
let a = new GlobalClass();
</script>
</body>
</html>
Copyright 2019 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
{
"name": "Content script loader test",
"version": "1.0.0",
"manifest_version": 2,
"content_scripts": [
{
"matches": ["file:///*"],
"js": ["content.js"],
"run_at": "document_start"
}
],
"web_accessible_resources": [
"inject.js"
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment