今天嘗試在iframe
中嵌入外部網站, 碰到了一些小問題.
如何讓自己的網站不被其他網站的iframe
引用?
我測試的時候發現我把iframe
的src
指定到github不起作用. 原來是它把X-Frame-Options
設置爲了DENY
, 這樣就禁用了別的網站的iframe
引用, 避免點擊劫持(clickjacking).
X-Frame-Options
有三個可能值: DENY
, SAMEORIGIN
, ALLOW-FROM uri
.
詳見: The X-Frame-Options response header
如何禁用自己iframe
中鏈接的外部網站的JS?
我發現我把一個外部網站引入到我的iframe
中時, 該網站的噁心JS會讓我的網頁跳轉到它的網站! 蛋疼. 但是我在測試的是否發現, Codepen就能夠避免這個跳轉, Console中有信息:
Unsafe JavaScript attempt to initiate navigation for frame with URL 'http://codepen.io/lzl124631x/pen/jWeOPL' from frame with URL 'http://keepvid.com/?url=https://www.youtube.com/watch?v=wY2vhSb3cVo'. The frame attempting navigation of the top-level window is sandboxed, but the 'allow-top-navigation' flag is not set.
(anonymous function) @ ?url=https://www.youtube.com/watch?v=wY2vhSb3cVo:108
?url=https://www.youtube.com/watch?v=wY2vhSb3cVo:579 GET http://www.5kplayer.com/kvads/keepvid-728-90.png net::ERR_BLOCKED_BY_CLIENT
原來是iframe
的屬性sandbox
的作用.
sandbox
屬性可以設置的值包括:allow-forms
allow-modals
allow-orientation-lock
allow-pointer-lock
allow-popups
allow-popups-to-escape-sandbox
allow-same-origin
allow-scripts
allow-top-navigation
如果給iframe
加上sandbox="allow-forms allow-scripts"
, 就會打開allow-forms
和allow-scripts
兩個選項, 其他的全部禁用.
如果想禁用讓外部網站的JS, 不要加allow-scripts
就好了.
如果想禁用外部網站的JS跳轉, 不要加allow-top-navigation
就可以了.
詳見: <iframe> Sandbox