Skip to content

Instantly share code, notes, and snippets.

@oussamahamdaoui
Last active January 14, 2025 06:03
Show Gist options
  • Save oussamahamdaoui/36d2e154503aec714c04f5df1c6edef3 to your computer and use it in GitHub Desktop.
Save oussamahamdaoui/36d2e154503aec714c04f5df1c6edef3 to your computer and use it in GitHub Desktop.
Detect devtools open and close events tested on Chrome and Safari,
/**
Any server would do as long as there is a path that sets a cookie named devtools
**/
//@ts-ignore
import { Bun } from 'bun';
import fs from "fs";
export default {
port: 3000,
async fetch(req) {
const url = new URL(req.url);
if(url.pathname == "/devtools"){
const response = new Response(`{"version":3,"sources":[],"mappings":"","names":[],"sourcesContent":[],"sourceRoot":"","file":""}`);
response.headers.set('Set-Cookie', 'devtools=1;');
return response
} else {
const fileContent = fs.readFileSync("index.html");
const response = new Response(fileContent);
response.headers.set('Content-Type', 'text/html')
return response;
}
}
};
<script>
(function () {
'use strict';
const reset = () => {
const t = document.createElement("script");
// this is where the magic happens
t.textContent = `//# sourceMappingURL=/devtools?v=${Date.now()}`;
document.head.appendChild(t);
t.remove();
}
reset();
let devtoolsOpen = false;
let prev = true;
const check = () => {
if (document.cookie.includes('devtools')) {
document.cookie = 'devtools=; Max-Age=0';
devtoolsOpen = true;
reset();
}
else {
devtoolsOpen = false;
}
if (prev !== devtoolsOpen) {
document.dispatchEvent(new CustomEvent('devtools', {
detail: devtoolsOpen,
}))
}
prev = devtoolsOpen;
setTimeout(check, 100);
}
setTimeout(check, 100);
})()
document.addEventListener('devtools', (e) => {
document.body.innerText = `devtools are ${e.detail ? "open" : "close"}`
})
</script>
@MrTomiCZ
Copy link

MrTomiCZ commented Jan 8, 2025

same

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