react native webview ios:我应该拦截ajax请求并设置请求的标题吗?
我使用react native的webview组件,情况是我想要截获ajax请求,并设置请求的自定义头,如User Agent、Referer、Cooike等,有什么解决方案吗?我遇到了同样的问题,我在React Native webview中包装了一个第三方web,在我的情况下,我需要向每个XHR(ajax)请求添加react native webview ios:我应该拦截ajax请求并设置请求的标题吗?,ajax,webview,header,react-native,Ajax,Webview,Header,React Native,我使用react native的webview组件,情况是我想要截获ajax请求,并设置请求的自定义头,如User Agent、Referer、Cooike等,有什么解决方案吗?我遇到了同样的问题,我在React Native webview中包装了一个第三方web,在我的情况下,我需要向每个XHR(ajax)请求添加授权头 我想出的一个技巧是将javascript注入到webview中,修改XMLHttpRequest.open的原型,以拦截来自web视图内部的所有请求 我们最终没有使用它,但
授权
头
我想出的一个技巧是将javascript注入到webview中,修改XMLHttpRequest.open的原型,以拦截来自web视图内部的所有请求
我们最终没有使用它,但在测试过程中它确实起了作用。我没有在Android上测试这个,但不明白为什么它不应该工作
下面是一个来自POC的片段,它描述了我的意思:
render() {
const accessTokenInterceptor = this.buildAccessTokenInterceptorInjection(this.state.accessToken, "api.example.com");
return (
<WebView
injectedJavaScript={accessTokenInterceptor}
javaScriptEnabled={true}
source={{
uri: 'https://example.com'
}}
/>
);
}
/**
* This name might require an explanation :)
*
* AFAIK there is no simple way of intercepting XHR requests that are being made
* from within the webview.
*
* A way to deal with this is to inject a script into the webview that modifies
* XMLHttpRequest.prototype.open so that everytime it is invoked a headers is added.
*
* Yes, this is a hack - if you find any better solution, I'll buy you a beer!
*
*/
buildAccessTokenInterceptorInjection(accessToken, whitelistedDomain) {
return `
(function() {
XMLHttpRequest.prototype.realOpen = XMLHttpRequest.prototype.open;
var openWithAccessToken = function(method, url, async, user, password) {
this.realOpen(method, url, async, user, password);
if (url.indexOf('${whitelistedDomain}') > 0) {
this.setRequestHeader('Authorization', 'Bearer ${accessToken}');
}
}
XMLHttpRequest.prototype.open = openWithAccessToken;
})()
`;
}
render(){
const accessTokenInterceptor=this.buildAccessTokenInterceptorInjection(this.state.accessToken,“api.example.com”);
返回(
);
}
/**
*此名称可能需要解释:)
*
*恐怕没有简单的方法可以拦截正在发出的XHR请求
*从webview中。
*
*处理这个问题的一种方法是向webview中注入一个脚本,该脚本修改
*XMLHttpRequest.prototype.open,以便每次调用它时都添加一个头。
*
*是的,这是一个黑客-如果你找到更好的解决方案,我会给你买一杯啤酒!
*
*/
buildAccessTokenInterceptorInjection(accessToken,whitelistedDomain){
返回`
(功能(){
XMLHttpRequest.prototype.realOpen=XMLHttpRequest.prototype.open;
var openWithAccessToken=函数(方法、url、异步、用户、密码){
realOpen(方法、url、异步、用户、密码);
if(url.indexOf('${whitelistedDomain}')>0){
setRequestHeader('Authorization','Bearer${accessToken}');
}
}
XMLHttpRequest.prototype.open=openWithAccessToken;
})()
`;
}
您找到解决方案了吗?