<!doctype html>
<html>
<body>
<button id="btn">点我打印 CallSite</button>
<pre id="log"></pre>
<script>
function capture() {
// 偷一张堆栈,拿到 CallSite 数组
let sites;
const prev = Error.prepareStackTrace;
Error.prepareStackTrace = (_, s) => (sites = s, s);
const dummy = new Error().stack;
Error.prepareStackTrace = prev;
const first = sites[0];
const log = document.getElementById('log');
// 先看方法在不在
if (typeof first.getScriptHash === 'function') {
log.textContent = 'getScriptHash 存在 → ' + first.getScriptHash();
} else {
log.textContent = 'getScriptHash 不存在';
}
}
document.getElementById('btn').onclick = capture;
</script>
</body>
</html>
function strToBuf(str) {
return new TextEncoder().encode(str); // 返回 Uint8Array,同时也是 ArrayBufferView
}
// 计算 SHA-256
async function sha256(str) {
const buf = strToBuf(str);
const hash = await crypto.subtle.digest('SHA-256', buf);
// 转十六进制
return [...new Uint8Array(hash)]
.map(b => b.toString(16).padStart(2, '0'))
.join('');
}
/* 演示 */
(async () => {
console.log(await sha256(`function capture() {
// 偷一张堆栈,拿到 CallSite 数组
let sites;
const prev = Error.prepareStackTrace;
Error.prepareStackTrace = (_, s) => (sites = s, s);
const dummy = new Error().stack;
Error.prepareStackTrace = prev;
const first = sites[0];
const log = document.getElementById('log');
// 先看方法在不在
if (typeof first.getScriptHash === 'function') {
log.textContent = 'getScriptHash 存在 → ' + first.getScriptHash();
} else {
log.textContent = 'getScriptHash 不存在';
}
}
document.getElementById('btn').onclick = capture;`));
// b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9
})();
// Node.js 版本
const crypto = require('crypto');
function sha256(str) {
return crypto
.createHash('sha256')
.update(str, 'utf8') // 指定编码,默认就是 utf8
.digest('hex'); // 直接输出 16 进制字符串
}
/* 演示 */
console.log(sha256(`
function capture() {
// 偷一张堆栈,拿到 CallSite 数组
let sites;
const prev = Error.prepareStackTrace;
Error.prepareStackTrace = (_, s) => (sites = s, s);
const dummy = new Error().stack;
Error.prepareStackTrace = prev;
const first = sites[0];
const log = document.getElementById('log');
// 先看方法在不在
if (typeof first.getScriptHash === 'function') {
log.textContent = 'getScriptHash 存在 → ' + first.getScriptHash();
} else {
log.textContent = 'getScriptHash 不存在';
}
}
document.getElementById('btn').onclick = capture;
`));