Skip to content

Instantly share code, notes, and snippets.

@dotproto
Last active May 5, 2023 02:20
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dotproto/42a9f6ce8484bbb01d1ea3bb31da672c to your computer and use it in GitHub Desktop.
Save dotproto/42a9f6ce8484bbb01d1ea3bb31da672c to your computer and use it in GitHub Desktop.
Inject video on page that has a CSP restrict that would normally prevent the video from being injected. To see this demo in action, load the extension unpacked and trigger the extension's action on the desired page.
// Copyright 2021 Google LLC.
// SPDX-License-Identifier: Apache-2.0
let videos = [
{
url: 'https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4',
type: 'video/mp4',
}, {
url: 'https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.webm',
type: 'video/webm',
},
];
function injectIframe(videos) {
let iframe = document.createElement('iframe');
iframe.src = chrome.runtime.getURL('video-iframe.html');
// Style the iframe to make it more obvious when we inject it
iframe.style = `
position: fixed;
top: 0;
left: 0;
width: 250px;
height: 141px;
`;
iframe.frameBorder = 0;
iframe.scrolling = 'no';
iframe.addEventListener('load', () => {
iframe.contentWindow.postMessage(videos, '*');
});
document.body.appendChild(iframe);
}
chrome.action.onClicked.addListener((tab) => {
chrome.scripting.executeScript({
target: {tabId: tab.id},
func: injectIframe,
args: [videos],
});
});
{
"name": "_Inject video on CSP-restricted page",
"version": "1.0",
"manifest_version": 3,
"action": {},
"background": {
"service_worker": "background.js"
},
"permissions": [
"scripting",
"activeTab"
],
"host_permissions": [
"<all_urls>"
],
"web_accessible_resources": [{
"resources": ["video-iframe.html"],
"matches": ["*://*/*"]
}]
}
<!--
Copyright 2021 Google LLC.
SPDX-License-Identifier: Apache-2.0
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="video-iframe.js"></script>
<style>html, body {padding: 0; margin: 0;}</style>
</head>
<body>
<video controls width="250"></video>
</body>
</html>
// Copyright 2021 Google LLC.
// SPDX-License-Identifier: Apache-2.0
window.addEventListener('message', (event) => {
let videoEl = document.querySelector('video');
for (let video of event.data) {
let source = document.createElement('source');
source.src = video.url;
source.type = video.type;
videoEl.append(source);
}
}, {once: true});
@GrahamMThomas
Copy link

Hey man, just wanted to let you know this is incredible and it helped me get my code working! Thanks for posting it!

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