I want to know the URL everytime it changes in webview. I searched online a lot. And according to that, I have done these changes. But it is still not working.
What am I doing wrong here. Why its not working.
It only logs for the first time. or it works when I click some other button on the screen.
What am I missing?
import React, { Component } from 'react';
import { Text, View, StyleSheet } from 'react-native';
import { WebView } from 'react-native-webview';
const initialUrl = 'https://www.youtube.com/';
let url = '';
class App extends Component {
state = {
url: initialUrl,
};
onNavigationStateChange = navState => {
console.log("navstate=== ",navState)
if (url!==navState.url) {
url = navState.url;
alert(url);
this.setState({
url: url
})
}
};
render() {
const { url } = this.state;
const injectedJs = `
var linkElements = document.getElementsByTagName("a");
linkElements[0].addEventListener("click", function() {
window.postMessage("addAccountSuccess?token=abc1234");
});
linkElements[1].addEventListener("click", function() {
window.postMessage("addAccountError");
`;
return (
<View style={{paddingTop: 24, flex: 1}}>
<Text style={{backgroundColor: 'black', color: 'white'}}>{ url }</Text>
<WebView
style={{ flex: 1}}
source={{
uri: initialUrl,
}}
injectedJavaScript={injectedJs}
startInLoadingState
scalesPageToFit
javaScriptEnabledAndroid={true}
javaScriptEnabled={true}
domStorageEnabled
startInLoadingState={false}
onNavigationStateChange={this.onNavigationStateChange.bind(this)}
onMessage={event => {
alert('MESSAGE >>>>' + event.nativeEvent.data);
}}
onLoadStart={() => {
console.log("LOAD START ");
}}
onLoadEnd={() => {
console.log('LOAD END');
}}
onError={err => {
console.log('ERROR ');
console.log(err);
}}
/>
</View>
);
}
}
export default App;