如果要防止頁面被iframe或frame嵌入,比較常用的方法是,在頁面上加入一串script做判斷,或者加入X-Frame-Options header。
X-Frame-Options有下列3個參數值可用:
deny
拒絕被任何嵌入頁面。
SAMEORIGIN
允許來至於相同domain的嵌入。
ALLOW-FROM uri
允許某個domain嵌入。
以下是用node.js寫得example:
var express = require('express'); var html = "from http://localhost:3001/SAMEORIGIN<br>" + '<iframe src="http://localhost:3001/SAMEORIGIN"></iframe><br>'+ 'from http://localhost:3001/deny<br>' + '<iframe src="http://localhost:3001/deny"></iframe><br>' + 'from http://localhost:3001/allow_from<br>' + '<iframe src="http://localhost:3001/allow_from"></iframe><br>'; (function(){ var app = express(); app.get('/', function(req, res){ res.send( html ); }); app.listen(3000); })(); (function(){ var app = express(); app.get('/', function(req, res){ res.send( html ); }); app.get('/SAMEORIGIN', function(req, res){ res.set('X-Frame-Options','SAMEORIGIN'); res.send('hello world'); }); app.get('/deny', function(req, res){ res.set('X-Frame-Options','deny'); res.send('hello world'); }); app.get('/allow_from', function(req, res){ res.set('X-Frame-Options','Allow\-From http://localhost:3001'); res.send('hello world'); }); app.listen(3001); })();
需先安裝node.js和express.js:
#使用npm安裝express npm install express #執行server.js node server.js
分別測試http://localhost:3000/ and http://localhost:3001/,其中allow-from測試時,似乎沒辦法取得正確結果,換成其他domain頁面一樣是可讀取的。