# 如何讓外部代碼“安全”運行？只是禁止eval（）？

## 最佳答案

• Use the sandbox attribute of an iframe for untrusted content.
• The sandbox attribute of an iframe enables restrictions on content within a iframe. The following restrictions are active when the sandbox attribute is set:

1. All markup is treated as being from a unique origin.

2. All forms and scripts are disabled.

3. All links are prevented from targeting other browsing contexts.
4. All features that triggers automatically are blocked.
5. All plugins are disabled.

It is possible to have a fine-grained control over iframe capabilities using the value of the sandbox attribute.

• In old versions of user agents where this feature is not supported, this attribute will be ignored. Use this feature as an additional layer of protection or check if the browser supports sandboxed frames and only show the untrusted content if supported.

• Apart from this attribute, to prevent Clickjacking attacks and unsolicited framing it is encouraged to use the header X-Frame-Options which supports the deny and same-origin values. Other solutions like framebusting if(window!== window.top) { window.top.location = location; } are not recommended.

請參閱我的其他答案，了解如何安全實施沙箱的詳細信息。