Last active
January 14, 2025 06:03
-
-
Save oussamahamdaoui/36d2e154503aec714c04f5df1c6edef3 to your computer and use it in GitHub Desktop.
Detect devtools open and close events tested on Chrome and Safari,
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
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; | |
} | |
} | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Tested on chrome and brave.
It just flooding the console with some img