Skip to content

Instantly share code, notes, and snippets.

@muralikg
Last active June 8, 2023 09:19
Show Gist options
  • Save muralikg/23cfed0b099b3df812bb2b27ba1be6a4 to your computer and use it in GitHub Desktop.
Save muralikg/23cfed0b099b3df812bb2b27ba1be6a4 to your computer and use it in GitHub Desktop.
puppeteer screen capture demo. Currently records 10 second video. Change the timeout in background.js with your own logic to stop the recording when necessary. Try with `node export.js`
/* global chrome, MediaRecorder, FileReader */
chrome.runtime.onConnect.addListener(port => {
let recorder = null
port.onMessage.addListener(msg => {
console.log(msg);
switch (msg.type) {
case 'REC_STOP':
console.log('Stopping recording')
if (!port.recorderPlaying || !recorder) {
console.log('Nothing to stop')
return
}
port.recorderPlaying = false
recorder.stop()
break
case 'REC_CLIENT_PLAY':
if (port.recorderPlaying) {
console.log('Ignoring second play, already playing')
return
}
port.recorderPlaying = true
const tab = port.sender.tab
tab.url = msg.data.url
chrome.desktopCapture.chooseDesktopMedia(['tab', 'audio'], streamId => {
// Get the stream
navigator.webkitGetUserMedia({
audio: false,
video: {
mandatory: {
chromeMediaSource: 'desktop',
chromeMediaSourceId: streamId,
minWidth: 1280,
maxWidth: 1280,
minHeight: 720,
maxHeight: 720,
minFrameRate: 60,
}
}
}, stream => {
var chunks=[];
recorder = new MediaRecorder(stream, {
videoBitsPerSecond: 2500000,
ignoreMutedMedia: true,
mimeType: 'video/webm'
});
recorder.ondataavailable = function (event) {
if (event.data.size > 0) {
chunks.push(event.data);
}
};
recorder.onstop = function () {
var superBuffer = new Blob(chunks, {
type: 'video/webm'
});
var url = URL.createObjectURL(superBuffer);
// var a = document.createElement('a');
// document.body.appendChild(a);
// a.style = 'display: none';
// a.href = url;
// a.download = 'test.webm';
// a.click();
chrome.downloads.download({
url: url,
//filename: "suggested/filename/with/relative.path" // Optional
});
}
recorder.start();
setTimeout(()=>{
recorder.stop()
}, 10000)
}, error => console.log('Unable to get user media', error))
})
break
default:
console.log('Unrecognized message', msg)
}
})
})
window.onload = () => {
if (window.recorderInjected) return
Object.defineProperty(window, 'recorderInjected', { value: true, writable: false })
// Setup message passing
const port = chrome.runtime.connect(chrome.runtime.id)
port.onMessage.addListener(msg => window.postMessage(msg, '*'))
window.addEventListener('message', event => {
// Relay client messages
if (event.source === window && event.data.type && event.data.type.startsWith('REC_CLIENT_')) {
port.postMessage(event.data)
}
})
document.title = 'pickme'
window.postMessage({ type: 'REC_CLIENT_PLAY', data: { url: window.location.origin } }, '*')
}
const puppeteer = require('puppeteer');
console.log(__dirname)
var options = {
headless: false,
args: [
'--enable-usermedia-screen-capturing',
'--allow-http-screen-capture',
'--no-sandbox',
'--auto-select-desktop-capture-source=pickme',
'--disable-setuid-sandbox',
'--load-extension=' + __dirname,,
'--disable-extensions-except=' + __dirname,
],
executablePath: 'google-chrome-unstable',
}
puppeteer.launch(options).then(browser=>{
return browser.pages().then(pages=>{
var page = pages[0];
return page.goto('http://tobiasahlin.com/spinkit/', {waitUntil: 'networkidle2'}).then(_=>{
return page.evaluate(()=>{
var session = {
audio: false,
video: {
mandatory: {
chromeMediaSource: 'screen',
},
optional: []
},
};
})
})
}).then(_=>{
// return browser.close()
})
})
{
"name": "Video Capture Attempt #1",
"version": "0.1.0",
"manifest_version": 2,
"background": {
"scripts": ["background.js"]
},
"content_scripts": [{
"matches": ["<all_urls>"],
"js": ["content_script.js"],
"run_at": "document_start"
}],
"permissions": [
"desktopCapture",
"<all_urls>",
"downloads"
]
}
@zeenalo
Copy link

zeenalo commented Jul 11, 2018

How to use?

@nollytainment
Copy link

Hey man! are you available for a quick project no more than 5hours task. i am ready to pay for your time to make modification to this script.

@ChrisHagan
Copy link

Would you mind pointing out the part of this that works around the Screen Sharing Request dialog please? I'm doing a very similar piece and it's a hurdle.

@Ventricule
Copy link

Ventricule commented Aug 19, 2019

Hey, that's great !
Exactly what I wanted to do since a day.
The only problem I have is that there is banners to say "chrome is actually controlled by puppeteer" and "tab is captured", and so, the size of the window is not the size I defined. Is there a way to hide the banners ? Or to record the viewport without consideration to the window size ? Or to record headless ?

@muralikg
Copy link
Author

@ChrisHagan sorry for the late reply but if you notice the document title is set to pickme and auto desktop source selection also set to the same value. This prevents the screen sharing request dialog box.

@Ventricule I have put together an example using xvfb to record headless.
Please check the Example and see if it solves your problem

@Ventricule
Copy link

@muralikg Thank you for Puppetcam ! I did a fork to use without XVFB (not existing on windows) and to add size and length params : https://github.com/Ventricule/puppetcam

@NiceGuyNimni
Copy link

Tiny note: Line 11 in export.js has double comma which causes an error since it adds an undefined arg

@svikas641
Copy link

Thank you

@SamuelScheit
Copy link

@steinathan
Copy link

I did a package for it: https://www.npmjs.com/package/puppeteer-stream

It works however i cant use a custom Page from maybe puppeteer-core

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