iframe或者window.open()添加请求头方法
首先我们要明白iframe是不能添加请求头的,这里我们能做的就是改造iframe里的src指向页面,通过异步请求,添加请求头,拿到html数据,再反写进iframe例如:在当前vue页面修改iframe<iframe src="./query.html" style="width: 100%;height: 450px;" frameborder="0"></iframe>
·
- 首先我们要明白iframe是不能添加请求头的,这里我们能做的就是改造iframe 里的src指向页面,通过异步请求,添加请求头,拿到html数据,再反写进iframe
例如:
在当前vue页面修改iframe
<iframe id="report_id" src="./query.html" style="width: 100%;height: 450px;" frameborder="0"> </iframe> //初始化方法 init(){ //发送请求得到html数据 this.$http.get(this.$route.query.url).then(res =>{ this.form=res; var iframeWin = this.$refs['report_id'].contentWindow; //向子页面发送参数 iframeWin.postMessage({ url: this.$route.query.url, data:res //页面html代码res }, '*'); }); }
在子页面query.html里面拿到父页面vue页面的参数data,将data里的html渲染进子页面的iframe<iframe id="app" name="app" style="width: 100%;height: 650px;" frameborder="0"> <script type="text/javascript"> window.URL=""; window.onload=function(){ //通过监听事件接收参数 window.addEventListener("message", function(e){ var iframe = window.frames['app']; //打开iframe.document iframe.document.open(); //iframe.document写入html数据 iframe.document.write(e.data.data); //iframe.document关闭 iframe.document.close(); }); } </script>
- window.open也是不能添加请求头的,
如果是跳转页面,可以像上面方法那样,通过iframe内塞入html页面代码;
如果是打印或者导出,可以通过iFrame.window.print()和XMLHttpRequest来实现.const iframe=window.frames['_print_pdf_frame']; $("iframe[name='_print_pdf_frame']").on("load",function(){ iframe.window.focus(); iframe.window.print(); }); iframe.window.focus(); iframe.location.href=url;//赋值iframe的路径
//导出pdf按钮事件 $(`.export-pdf`).click(function(){ const urlParameters=buildLocationSearchParameters(); const url=window._server+'/pdf'+urlParameters; windowOpen(url,'.pdf'); }); function windowOpen(url,typeName){ var xhr = new XMLHttpRequest(); var fileName = window.fileName + typeName; // 文件名称 xhr.open('GET', url, true); xhr.responseType = 'blob'; xhr.setRequestHeader('token',window.token); xhr.onload = function(res) { if (this.status === 200) { var type = xhr.getResponseHeader('Content-Type'); var blob = new Blob([this.response], {type: type}); if (typeof window.navigator.msSaveBlob !== 'undefined') { /* * For IE * >=IE10 */ window.navigator.msSaveBlob(blob, fileName); } else { /* * For Non-IE (chrome, firefox) */ var URL = window.URL || window.webkitURL; var objectUrl = URL.createObjectURL(blob); if (fileName) { var a = document.createElement('a'); if (typeof a.download === 'undefined') { window.location = objectUrl; } else { a.href = objectUrl; a.download = fileName; document.body.appendChild(a); a.click(); a.remove(); } } else { window.location = objectUrl; } } } } xhr.send(); };
相关资料参考:
XMLHttpRequest 对象
XMLHttpRequest 及其open()的用法_小木木的开发日常-CSDN博客
更多推荐
已为社区贡献1条内容
所有评论(0)