我如何拦截来自iframe的http请求
How can I intercept http requests from an iframe?
我在我的网页中设置了一个iframe的URL。我必须知道哪些http请求是从这个URL更改触发的(CSS,脚本,图像等加载的URL)。我截获了XMLHttpRequest,但是这个对象从来没有被调用过…
如何拦截这些http请求?
是否有其他方法来"加载"?一个iframe并获得所有触发的URL请求?
下面是我的代码:(function(xhr){
var pt = xhr.prototype;
pt._open = pt.open;
pt.open = function(){
console.log('Open called...');
this._open.apply(this, arguments);
})(XMLHttpRequest);
...
$('#iframe').attr('src', 'http://www.stackoverflow.com');
一个<iframe />
与父窗口有不同的window
,因此,当你覆盖XMLHttpRequest
时,你覆盖了父窗口中的一个,而不是 <iframe />
窗口中的一个。
不幸的是,同源策略阻止您访问<iframe />
的window
,因此您对此无能为力。
即使SOP没有在这里发挥作用,当你可以拦截AJAX请求时,你将无法拦截资产请求(CSS, JS,图像)。
你最好的选择是在你的服务器上使用代理,并通过那里路由iframe请求;通过代理重写所有的资产URL,而不是直接访问(但即使这样你也有不可能跟踪的边缘情况,如JavaScript包括其他资产等)
这应该是可能的,只要你可以更新iframe代码,如果你不能,通过在iframe at iframe load事件中注入一些代码,如下所述。
这个typescript sorry可以翻译成javascript ..
<iframe [src]="iframeSiteUrl" title="myIframe" (load)="injectCustomHttpInterceptorHook() id="my-iframe" #iframeObj></iframe>
@ViewChild(iframeObj, {static: false}) iframeObj: ElementRef;
injectCustomHttpInterceptorHook (){
this.iframeWindow = (this.iframeObj.nativeElement.contentWindow || this.iframeObj.nativeElement.contentDocument);
let xhrObj =this.iframeWindow.XMLHttpRequest.prototype.open;
var parentObj = this;
this.iframeWindow.XMLHttpRequest.prototype.open = function (method, url, async, user, password) {
//intercepted here
this.addEventListener('load', function() {
console.log('load: ' + this.responseText);
});
xhrObj.apply(this, arguments);
const oidcToken = JSON.parse(window.localStorage.getItem(parentObj.localstorageKey));
const accessToken = oidcToken.access_token;
this.setRequestHeader('Authorization', "Bearer " + accessToken);
}
}
相关文章:
- Meteor如何接收HTTP请求
- 在我的情况下,如何进行http请求
- 使用插件收听Firefox标签的http请求
- http请求使用html而不是json进行响应
- 在node-js路由中发出http请求
- 是否可以在没有HTTP请求或<输入>
- Acync JS HTTP请求通知请求
- PhantomJs在控制台中发出http请求时不会返回任何状态
- PHP处理来自一个页面的http请求,并将其显示在另一个页面上
- Firefox插件-如何发出http请求
- 验收测试主要针对传出的http请求
- 验证HTTP请求来自NFC标签上的点击
- 如何制作'http请求'在Node js中同步
- 为什么我在Cloud9中的http请求总是返回错误
- AngularJS Typeahead和$http请求限制
- HTTP请求使用cURL,但在浏览器中使用javascript时会得到CORS响应
- 如何使用Chrome扩展API获取网页的所有HTTP请求
- 将http请求中的数据传递给C#控制器
- 在初始化路由之前发送$http请求
- 从客户端捕获 HTTP 请求(包括 ajax)