使用nodejs將第三方頁面嵌入到系統(tǒng)中
最近在公司遇到一個特殊的需求,需要將第三方的頁面嵌入到系統(tǒng)中仅孩,并更改內部的樣式菜职。
如何將外來的頁面嵌入到系統(tǒng)中?
百度查找了各路大神的方案肉微,得出結論:js不允許訪問不同源iframe內的元素匾鸥。所以解決方案只能寫一個后臺來搞定這件事情。當時想寫java后臺碉纳,后面想想部署等相對復雜勿负,最終使用了強大的nodejs。
首先嘗試前端js能不能獲取到不同源的iframe內的dom元素劳曹。
tip:試了才知道奴愉,映象才深刻。話不多說直接上代碼铁孵。
html
<div class="col-xl-3">
<button>刪除</button>
</div>
<div class="col-xl-9">
<!--不同源的百度頁面-->
<iframe width="100%" height="800px" src="http://www.baidu.com"></iframe>
<!--同源的百度頁面-->
<!--<iframe width="100%" height="800px" src="/baidu"></iframe>-->
</div>
js
//點擊按鈕就將百度頁面頭和大logo去掉
$('button').click(function () {
var $iframe=$('iframe');
$iframe.contents().find('head').remove();
$iframe.contents().find('#lg').remove();
});
結果是點擊了沒有任何反應锭硼。
使用nodejs中轉頁面
使用express做接口,使用superagent做頁面的請求库菲。
routes代碼如下:
var express = require('express');
var router = express.Router();
var path = require('path');
//使用agent自動處理cookie
const agent = require('superagent').agent();
router
.get('/', function(req, res, next) {
res.sendFile(path.join(__dirname, '../html', 'iframe.html'));
})
.get('/baidu',(req,res) => {
agent.get('http://www.baidu.com',(areq,ares) => {
res.end(ares.text);
})
});
module.exports = router;
當請求/baidu
時agent會先將頁面請求下來然后再返回給頁面账忘,這樣就簡單地處理了一個不同源問題。
我們修改html的內容,如下:
<div class="col-xl-9">
<!--不同源的百度頁面-->
<!--<iframe width="100%" height="800px" src="http://www.baidu.com"></iframe>-->
<!--同源的百度頁面-->
<iframe width="100%" height="800px" src="/baidu"></iframe>
</div>
再次打開鳖擒,點擊刪除按鈕頁面的head和lg成功被刪除溉浙。
image
至此可以使用nodejs來解決這個問題。最后貼上實際代碼蒋荚。
js
'use strict';
// 要代理的url
const proxyUri = 'http://xxx.xxx.xxx';
var express = require('express');
var cookie = require('cookie-parser');
var events = require('events');
//本來想在nodejs中處理dom的
var cheerio = require('cheerio');
const superAgent = require('superagent');
const httpProxy = require('http-proxy');
var router = express.Router();
router.use(cookie());
const agent = superAgent.agent(express);
var emitter = new events.EventEmitter();
emitter.on("setCookeie", cookieReset);
let proxy = httpProxy.createProxyServer({
target: proxyUri,
changeOrigin: true,
cookieDomainRewrite: {
'*': proxyUri
},
secure: false,
});
proxy.on('error', function (err, request, response) {
response.writeHead(500, {
'Content-Type': 'text/plain',
});
console.log(err);
response.end('server error');
});
//設置跨域訪問
router.all('*', function (req, res, next) {
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By", ' 3.2.1');
res.header('Access-Control-Allow-Origin', "*");
res.header('Access-Control-Allow-Credentials', true);
next();
});
router.use(express.static('../static/'));
login();
/**
* 登錄獲取cookie
*/
function login(isFlag) {
agent
.post('http://xxx.xxx.xxx/login')
.type('form')
.send({username: 'admin'})
.send({password: 'admin'})
.send({remembercb: 'remember-me'})
.redirects(0)
.end(function (sreq, sres) {
let cookie = sres.headers['set-cookie'];
emitter.emit("setCookeie", cookie, isFlag);
});
}
/**
* 將設置的cookie與express共享
* @param cookie
*/
function cookieReset(cookie, isFlag) {
router.all('*', function (req, res, next) {
res.header('set-cookie', cookie[0]);
next();
});
if (isFlag) return;
router
.get('/', function (req, res) {
res.sendFile('../static/index.html');
})
.get('/mit/*', function (req, res) {
let proxy_url = proxyUri + (req.url).replace('mit', 'cmp');
console.log('proxy:', proxy_url);
//這里注意agent的緩存戳稽,它會緩存cookie,這樣導致某cookie失效后就無法使用了期升。
//這里推薦你這樣做 superAgent.agent();
agent
.get(proxy_url)
.end(function (areq, ares) {
if (ares.text) {
res.end(ares.text);
}else {
res.end('<h2>請求失敗</h2>');
}
});
})
.all('/mitc/*', function (req, res) {
if (req.url === '/mitc/login') {
console.log('cookie超時惊奇,請求登錄頁了');
login(true);
res.redirect('/');
} else {
proxy.web(req, res);
return;
}
});
};
module.exports = router;
基本思想是:開始使用anget登錄到該網站,并將
cookie
保存并設置給express
播赁。之后
使用http-proxy
代理來自iframe
內的所有請求(iframe內的css颂郎、js等)。這里頁面cookie
會過期容为,
這里并不希望它調到登錄頁面乓序,所有攔截它的登錄請求,再次登錄坎背。
ok成功解決了問題替劈,一個好周末就來了。
出現(xiàn)了一個cookie緩存的bug得滤,如果你和我一樣的代碼陨献,那么必須注意agent的緩存cookie(原因未知),使用必須看一下懂更。