Tips——RN webview如何实现首次加载自动登录及后续定时登录
一、首次加載自動登錄
1.問題分析
Rn webview有自動登錄機制,即如果是需要登錄的頁面,在首次登錄后,二次進入不需登錄。但第一次進入頁面必須要進行密碼輸入和登錄操作。所以,如果要實現首次自動登錄,必須要在webview加載之前進行手動登錄操作。
2.解決
利用RN webview的handleWebViewNavigationStateChange和injectedJavaScript等api進行操作:
webview:
<WebViewref={ref => (this.webview = ref)}onNavigationStateChange={this.handleWebViewNavigationStateChange}source={{ uri: this.state.source }} /> handleWebViewNavigationStateChange:// 注意,此函數可能會在webview加載時被多次執行,為避免重復fetch請求,需設置一個a值做bool判斷let a = false; handleWebViewNavigationStateChange = newNavState => {const { url } = newNavState;// redirect somewhere else// 做關鍵詞判斷if (url.includes(xxxx) && !a) { fetch( URL , {credentials: 'same-origin',method: 'POST',headers: {'Content-Type': 'application/json'},body: JSON.stringify(BODY)}).catch(err => {throw err;}).then(resp => {let newURL = "xxxxx" // 登錄后的跳轉URLlet redirectTo = 'window.location = "' + newURL + '"';
// 注入新的跳轉鏈接this.webview.injectJavaScript(redirectTo); }); a = true;}};
webview通過injectJavaScript注入代碼到pc端,進行手動跳轉操作,即可達到自動登錄效果。
?
二、webview定時自動登錄
HTML設定距離最后一次操作的8小時內若無任何用戶操作,即會注銷用戶,提示超時信息。
所以設定每7小時自動登錄一次,即可避免頁面超時。
handleWebViewNavigationStateChange:
handleWebViewNavigationStateChange = newNavState => {console.log(newNavState)const { url } = newNavState;var _this = this;// redirect somewhere elseif (url.includes('dom') && !a) {//首次登錄彈框:首次加載,時間較長,請耐心等待this.setState({ firstLogin: true })//首次加載自動登錄this.autoLogin(_this);// 每7個小時后定時自動登錄setInterval(() => {this.autoLogin(_this)}, 1000*60*60*7)a = true;} };autoLogin:
autoLogin(_this) {fetch('http://dom.inwhile.com/api/login/2', {credentials: 'same-origin',method: 'POST',headers: {'Content-Type': 'application/json'},body: JSON.stringify({"name": 'dev@basdom.com', "pwd": "Abcd12345"})}).catch(err => {throw err;}).then(resp => {let newURL = 'http://dom.inwhile.com/app/observer/'+ this.state.itemId + '/'+ this.state.name_en + '/'+ this.state.newId + '/'+ this.state.page_Id; if( this.state.page_Id !== '' ) {this.setState({ source: newURL, firstLogin: false });let redirectTo = 'window.location = "' + newURL + '"';this.webview.injectJavaScript(redirectTo); } }); }?
補充:
原本的解決方法(太過雞肋。。。)如下:
webview過期后自動登錄:
當webview加載的網頁過期后,HTML端可能會彈出(alert)警告窗口,并跳轉到登錄頁。因此,過期后自動登錄的實現需要解決三個問題:獲取網頁端過期的時間節點提醒、再次自動登錄和取消alert提醒(屏蔽彈出框)。
1.獲取HTML過期提醒
HTML需向RN傳遞消息:
window.postMessage(JSON.stringify({msg: "out of date!" }))RN接收消息:
onMessage = event => {const action = JSON.parse(event.nativeEvent.data)if (action.msg == "out of date") {//2.屏蔽alert彈框 const spamAlertScript =` alert = function(str) {return; //什么事也不做,等于屏蔽了它 }alert( "已經無效! ");` this.webview.injectJavaScript(spamAlertScript);//3.再次自動登錄setTimeout(() => {this.autoLogin(); }, 500);}} }?
—— 完 ——
轉載于:https://www.cnblogs.com/bbcfive/p/10889207.html
總結
以上是生活随笔為你收集整理的Tips——RN webview如何实现首次加载自动登录及后续定时登录的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Javascript - Vue - w
- 下一篇: [MySQL实践] 实践记录