在開放使用者自訂腳本的平台(如部落格、CMS),為安全或體驗需求,可能需要禁用特定全域函數(如 alert、document.write)。本文介紹「方法重寫」技巧:覆蓋目標函數為空函數,並討論其限制與更完善的沙箱方案。
// 禁用 alert
window.alert = function() { /* 什麼都不做 */ };
// 禁用 document.write
document.write = function() { /* 什麼都不做 */ };
// 測試
alert("這不會彈出"); // 無反應
document.write("也不會寫入"); // 無反應
原理:JS 函數為一等公民,全域函數屬於 window 或 document 物件屬性,直接重新賦值即可攔截後續呼叫。
<!-- 頁面最上方,優先載入 -->
<script src="/js/disable-dangerous-functions.js"></script>
<!-- 使用者自訂腳本區塊 -->
<div id="user-content">...</div>
disable-dangerous-functions.js 內容:
(function() {
const noop = () => {};
// 禁用清單
window.alert = noop;
window.confirm = noop;
window.prompt = noop;
window.open = noop; // 禁用彈窗
document.write = noop;
document.writeln = noop;
// 禁用 DOM 破壞性方法
Element.prototype.remove = noop; // 謹慎:影響所有元素
// 若需更精細,可用 Proxy 或 Object.defineProperty 保護特定實例
})();
| 問題 | 說明 |
|---|---|
| 僅攔截直接呼叫 | 若使用者代碼用 eval("alert(1)")、Function("alert(1)")()、setTimeout("alert(1)") 等字串執行,重寫無效。 |
| 原型鏈繞過 | Window.prototype.alert.call(window) 仍可呼叫原生(若未一併重寫原型)。 |
| iframe 隔離失效 | 父頁面重寫不影響 iframe 內的 window.alert。 |
| 移除腳本標籤 | 使用者可用 document.querySelector('script[src="..."]').remove() 移除禁用腳本。 |
| 破壞正常功能 | 自身業務代碼若需 alert 除錯將失效。 |
<!-- 1. Content Security Policy 禁止 inline script、eval、外部腳本 -->
<meta http-equiv="Content-Security-Policy"
content="script-src 'self' https://trusted.cdn.com; object-src 'none'; base-uri 'self';">
<!-- 2. 沙箱 iframe 載入使用者內容 -->
<iframe sandbox="allow-scripts allow-same-origin"
srcdoc="<script>alert(1)</script>"></iframe>
<!-- sandbox 屬性可細粒度控制:allow-forms, allow-popups, allow-top-navigation 等 -->
Object.freeze(window)(非標準)或 Object.defineProperty 設定 writable: false, configurable: false 提高繞過難度。