Redirect WebView with other domain in React Native
I'm trying to redirect links from another domain to the device's default browser.
For example:
- if the link is http://domain.io, stay in the WebView;
- if the link is http://domain.io/page, we stay in the WebView;
- and if the link is http://mylink.io/, we redirect the user to the default browser of the device and we leave the WebView.
I tried a lot of things, but I still can not make it work. I think about using onNavigationStateChange
with Linking.
Thanks for your help.
import React from 'react';
import { StyleSheet, View, WebView } from 'react-native';
import { Constants } from 'expo';
export default class App extends React.Component {
render() {
return (
<View style={styles.container}>
<View style={styles.statusBar} />
<WebView
source={{uri: 'https://example.com'}}
renderError={() => alert('Merci de vérifier votre connexion Internet', 'Internet non disponible')}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
statusBar: {
backgroundColor: "#1D3B57",
height: Constants.statusBarHeight,
}
});
1 answer
-
answered 2018-04-14 15:44
Stackia
Solution 1:
onNavigationStateChange(e) { if(e.url !== this.state.oldUrl) { // If url changed if(/youtube.com/.test(e.url)) // RegExp { this.refs.WEBVIEW_REF.goBack() Linking.canOpenURL(e.url).then(supported => { if (supported) return Linking.openURL(e.url) }) } this.setState({ oldUrl: e.url }) } }
Solution 2:
Consider looking into this PR to expose native
shouldOverrideUrlLoading
method to JS. It might be a bit complex to do this.
See also questions close to this topic
-
handling backpress in bottom navigation for fragments doesnt work properly
Hi i have a problem with bottom navigation handling the fragments on backpress.So my problem is when i click on back button the last visited fragment loads but the icon of bottomnavigation remains the same in other words the last visited fragment loads in current tab and not int the tab it should i saw some question son SO related to this but still no success Here are the questions i saw onBackPress it should take to Home fragement in bottom Navigation How to handle bottom navigation perfectly with back pressed So here i dont know how to manage that can someone please guide me here my mainactivity code
public class MainActivity extends AppCompatActivity { FrameLayout frameLayout; FragmentManager fragmentManager; Fragment fragment; BottomNavigationView bottomNavigationView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //BottomNavigationView b=findViewById(R.id.bottom_nav); fragmentManager = getSupportFragmentManager(); if (findViewById(R.id.frame_container) != null) { if (savedInstanceState != null) { return; } HomeFragment homeFragment = new HomeFragment(); FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); transaction.replace(R.id.frame_container, homeFragment,null); transaction.addToBackStack(null); /* Comment this line and it should work!*/ //transaction.addToBackStack(null); transaction.commit(); } bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_nav); //final SeekBar sb = (SeekBar) findViewById(R.id.sb); bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { Fragment fragment = null; Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.container); switch (item.getItemId()) { case R.id.navigation_home: if(!(currentFragment instanceof HomeFragment)) { fragment = new HomeFragment(); loadFragment(fragment); } break; case R.id.navigation_feed: if(!(currentFragment instanceof FeedFragment)) { fragment = new FeedFragment(); loadFragment(fragment); } break; case R.id.navigation_event: if(!(currentFragment instanceof EventsFragment)) { fragment = new EventsFragment(); loadFragment(fragment); } break; case R.id.navigation_nearby: if(!(currentFragment instanceof NearbyFragment)) { fragment = new NearbyFragment(); loadFragment(fragment); } break; case R.id.navigation_profile: if(!(currentFragment instanceof ProfileFragment)) { fragment = new ProfileFragment(); loadFragment(fragment); } break; } return true; } }); } @Override public void onBackPressed() { super.onBackPressed(); } private void loadFragment(Fragment fragment) { // HomeFragment homeFragment = new HomeFragment(); FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); transaction.replace(R.id.frame_container, fragment,null); transaction.addToBackStack(null); /* Comment this line and it should work!*/ //transaction.addToBackStack(null); transaction.commit(); // load fragment //HomeFragment homeFragment = new HomeFragment(); } }
-
Could not resolve library project circleCI
I am quite new to circleCI and want to use it for CI pipeline for android. My
.circleci/config.yml
is below :version: 2 jobs: build: working_directory: ~/code docker: - image: circleci/android:api-25-alpha environment: JVM_OPTS: -Xmx3200m steps: - checkout: post: - git submodule sync - git submodule update --init # use submodules - cp -r licenses/. $ANDROID_HOME/licenses - restore_cache: key: jars-{{ checksum "build.gradle" }}-{{ checksum "app/build.gradle" }} - run: name: Download Dependencies command: ./gradlew androidDependencies - save_cache: paths: - ~/.gradle key: jars-{{ checksum "build.gradle" }}-{{ checksum "app/build.gradle" }} - run: name: Run Tests command: ./gradlew lint test - store_artifacts: path: app/build/reports destination: reports - store_test_results: path: app/build/test-results
when I build the project I get error
Could not resolve project "library_project"
. why circle CI not able to detect submodule in my project? Any help will be appreciated. -
How to properly call releaseNetworkRequest(PendingIntent) when PendingIntent is no longer available
I am trying to request the network, so I build the NetworkRequest and I build the PendingIntent,
ConnectivityManager conn_manager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); NetworkRequest net_req; net_req = new NetworkRequest.Builder() .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR) //Data Network? .addTransportType(NetworkCapabilities.TRANSPORT_WIFI) //Wifi .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) //This might be what need internet permission .addCapability(NetworkCapabilities.NET_CAPABILITY_MMS) .build(); Intent intent_sent = new Intent(activity, Service_MmsNetworkAvailable.class); PendingIntent pending_intent_net_req_received = PendingIntent.getService(activity, 0, intent_sent, PendingIntent.FLAG_ONE_SHOT); conn_manager.requestNetwork(net_req, pending_intent_net_req_received);
Then once the Service runs from the PendingIntent calling it, I am doing some Network stuff inside the Service and then when I'm done I believe I need to call releaseNetworkRequest(PendingIntent).
But here's the whole problem of mine, how do I reference the PendingIntent that started the Service from inside the Service? There is no guarantee that the Activity that created the NetworkRequest and PendingIntent will still be alive so I cannot rely on returning to that Activity to be able to call releaseNetworkRequest(PendingIntent) where I have reference to the PendingIntent.
Android specifically states that you must pass in the same PendingIntent into releaseNetworkRequest(PendingIntent) that you passed into conn_manager.requestNetwork(net_req, pending_intent_net_req_received);
So how is a developer supposed to releaseNetworkRequest(PendingIntent)?
Can I somehow reference the PendingIntent from the Service? I understand that PendingIntents stay alive even after the Activity that called it parishes into the abyss.
I must be missing something here, PendingIntents call Activities, Receivers, and Services, none of which I see can reference back to the original PendingIntent. Furthermore, NULL cannot be passed into releaseNetworkRequest(PendingIntent) according to Android documentation?
Also just to note, I am only doing this because startUsingNetworkFeature() is deprecated and developers are encouraged to use NetworkRequest(), arg!!!
I am literally stuck here now with no way to go, this is rare to be so backed into a corner here if anyone can shed light on this predicament of mine I would be grateful.
-
iOS - Object C - Cant render pixel with UInt8
I try to catch an average color from certain image with CIAreaAverage. The cacthing operation goes well , outputImage from the filter gave me single pixel CIImage;
the problem occur when attempt to catch R/G/B informations with uint8_t
"pixel" (uint8_t) always empty (" ").
I'm pretty sure my render context is not nil , only "render" operation goes wrong.
I have no idea how to catch R/G/B data out from CIImage correctly . Please guide me , thanks .
-
Send Http Request to .Net Server
i want to send post request to .Net server. there is my code for post request:
public func SendPostHttpRequest(baseURL: String, parameter: [String:Any], closure:@escaping ((_ success:JSON,_ error:NSError?) -> Void)) { let manager = Alamofire.SessionManager.default if let url = URL(string: baseURL) { var urlRequest = URLRequest(url: url) urlRequest.setValue("text/html; charset=utf-8", forHTTPHeaderField: "Content-Type") urlRequest.setURLEncodedFormData(parameters: parameter) manager.request(urlRequest).responseString { response in debugPrint(" HTML error -------> \(response)") } manager.request(urlRequest).responseJSON { response in switch response.result { case .success(let JSON) : closure(JSON,nil) case .failure(let error): closure(nil,error as NSError) debugPrint("get error ---> \((error.localizedDescription)) ") } } } }
that is define Extension for set URLEncodedFormData to request
extension URLRequest { private static let alloweCharacters = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 -_.*@$!#/:+[]\n") public mutating func setURLEncodedFormData(parameters: [String: Any]) { var encodedParameters = "" for (key, value) in parameters { if !encodedParameters.isEmpty { encodedParameters += "&" } encodedParameters += URLRequest.urlEncoded(value: key) ?? "" encodedParameters += "=" let valuee = value if let boolValue = valuee as? Bool { encodedParameters += "\(boolValue)" } if let intValue = valuee as? Int { encodedParameters += "\(intValue)" } if let stringValue = valuee as? String { encodedParameters += (URLRequest.urlEncoded(value: stringValue) ?? "") } } self.httpMethod = "POST" self.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") self.httpBody = encodedParameters.data(using: .utf8) } private static func urlEncoded(value: String?) -> String? { return value?.addingPercentEncoding(withAllowedCharacters: alloweCharacters)!.replacingOccurrences(of: " ", with: "") } }
i have an issue in send variables with different types to server. in server side i get this error: Object reference not set to an instance of an object.
I think because I'm sending all the parameters to the string, the server side does not figure out the bool and integer variables. how can solve this problem? Thanks for all the comments.
-
Xamarin forms: Launcher icon for ios
I am trying to set the launcher icon for xamarin forms ios project from Mac.
I do the following things but still showing the default icon.
1.Double-Click the Info.plist file in the Solution Explorer to open it for editing.
2.Scroll down to the App Icons section.
3.From the Source dropdown list, select Migrate to Asset Catalogs.
4.Open Assets.xcassets and select App icons from the list.
5.Select the image file for the required type.
Is there any additional set up for this task? I refer this blog: https://docs.microsoft.com/en-us/xamarin/ios/app-fundamentals/images-icons/app-icons?tabs=vsmac
Thanks in advance.
-
React Native Navigation Not Working
While navigating, switching from the first screen to the second screen is running. But I can not switch to the third screen from the second screen. I want to switch from the second screen to the third screen. I do not know where I made mistakes. I share the codes below. Can you help me. ? Thank you
Respects
import React, { Component } from 'react'; import { WebView, AppRegistry, StyleSheet, Text, View, Button } from 'react-native'; import { StackNavigator } from 'react-navigation'; class App extends Component { static navigationOptions = { title: 'App', }; OpenSecondActivityFunction = () => { this.props.navigation.navigate('Second'); } render() { return ( <View style={styles.container}> <Button onPress = { this.OpenSecondActivityFunction } title = 'Open Second Activity'/> </View> ); } } class SecondActivity extends Component { static navigationOptions = { title: 'SecondActivity', }; OpenThirdActivityFunction = () => { this.props.navigation.navigate('Third'); } render() { return( <View style={{ flex: 1}}> <Button onPress = { this.ThirdActivityFunction } title = 'Open Third Activity'/> </View> ); } } class ThirdActivity extends Component { static navigationOptions = { title: 'ThirdSecondActivity', }; render() { return( <View style={{ flex: 1}}> <Text>3</Text> </View> ); } } export default ActivityProject = StackNavigator( { First: { screen: App }, Second: { screen: SecondActivity }, Third: { screen: ThirdActivity } }); const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, },ActivityNameTextCss: { fontSize: 22, color: 'black', textAlign: 'center', }, }); AppRegistry.registerComponent('ActivityProject', () => ActivityProject);
-
iOS builds (ipa file) generated by Expo is too large
I'm using Expo for a react native project. I used to get apk and ipa files close to 30 MB when I use
exp build:android
andexp build:ios
. Recently I updatedexp
version to53.0.0
and added an iPhone X to my Apple developer account. Since then I'm getting ipa file size above 170MB. I have not made any changes to my code orapp.json
. Does anyone have any idea why this is happening?I know this doesn't matter when I upload to App Store or Test Flight, but this is not an option for my project since we are using enterprise distribution and Diawi for testing purposes.
-
KeyboardAvoidingView not working as expected
I'm trying to work with either
KeyboardAwareScrollView
orKeyboardAvoidingView
but somehow both results in the same behaviour within the app. As you can see in the pictures below, the keyboard is still covering the password field:Without Keyboard With Keyboard Here's a snippet of my code:
const { fields, showLabel, buttonTitle, onForgotPassword} = this.props; return ( <KeyboardAvoidingView style={styles.container} behavior="padding"> <Image style={styles.image} source={require('../../../../assets/images/logo2.png')}/> <View style={styles.wrapper}> { (!isEmpty(this.state.error['general'])) && <Text style={styles.errorText}>{this.state.error['general']}</Text> } { fields.map((data, idx) => { let {key, label, placeholder, autoFocus, secureTextEntry} = data; return ( <AuthTextInput key={key} label={label} showLabel={showLabel} placeholder={placeholder} autoFocus={autoFocus} onChangeText={(text) => this.onChange(key, text)} secureTextEntry={secureTextEntry} value={this.state[key]['value']} error={this.state.error[key]}/> ) }) } <Button raised title={buttonTitle} borderRadius={4} containerViewStyle={styles.containerView} buttonStyle={styles.button} textStyle={styles.buttonText} onPress={this.onSubmit}/> { this.props.onForgotPassword !== null && <Text style={styles.forgotText} onPress={onForgotPassword}> Forgot password?</Text> } </View> </KeyboardAvoidingView> ); }
Can anyone help show me what I did wrong?
Cheers!
-
Ios, image in webview can't see correcty
I have a page inside an app (webview) made with html with 6 icons with Android this page is always display correctly, but with IOS the icons are distorted. It doesn't happen always but it happens often.
Sometimes the images are show right but when I scroll down the page and then I go back the problem still.
Could you help me?
Thanks
-
React native webview is not loading in android device
I am trying to load the graph inside the webview. It is working both in android and iOS simulator. When I was trying to load the same in android device, when the usb is connected to the device it is loading without any error but when the cable is disconnected from the device it is giving the following error Encountered an error loading page. Error Is :-
{"canGoForward":false,"code":-6,"canGoBack":false,"description":"net:ERR_CONNECTION_REFUSED","loading":false}
I am trying to load the following url
const LoacalWebURL = require('./Graphs/polarblock.html'); const LoacalWebURL1 = require('./Localgraph/forced.html'); const LoacalWebURL2 = require('./Localgraph/bump_chart/index.html'); // The web view code where I am trying to load the above url: <WebView style = {styles.WebViewStyle} source={LoacalWebURL1} javaScriptEnabled={true} domStorageEnabled={true} startInLoadingState={true} /> <WebView style = {styles.WebViewStyle} source={LoacalWebURL2} javaScriptEnabled={true} domStorageEnabled={true} startInLoadingState={true} />
-
Android loginvia facebook in pinterest is not working in webview
Android - Am loading a following url in webview "https://www.pinterest.com", it loads successfully, but when i click on login via facebook or login via google in pinterest it's loading a blank screen rather than loading the actual result, below is my code, please help me. The same code is working for other urls, but not for Pinterest alone.
public class Pinterest extends Fragment { private WebView wv1; String url="https://www.pinterest.com"; private ProgressBar progress; View mView; WebSettings settings; ImageView back,top; public Pinterest() { // Required empty public constructor } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment mView= inflater.inflate(R.layout.pinterest, container, false); wv1 = mView.findViewById(R.id.pin_webView); progress = mView.findViewById(R.id.pin_progressBar); back= mView.findViewById(R.id.go_back); top= mView.findViewById(R.id.goToTop); progress.setMax(100); settings = wv1.getSettings(); settings.setJavaScriptEnabled(true); settings.setAllowContentAccess(true); settings.setDomStorageEnabled(true); wv1.setWebViewClient(new myWebClient()); wv1.setVerticalScrollBarEnabled(true); wv1.setHorizontalScrollBarEnabled(true); wv1.loadUrl(url); progress.setProgress(0); wv1.setWebChromeClient(new WebChromeClient() { @Override public void onProgressChanged(WebView view, int newProgress) { setValue(newProgress); if (newProgress == 100) { progress.setVisibility(View.GONE); } super.onProgressChanged(view, newProgress); } }); back.setOnClickListener(v -> { if(wv1.canGoBack())wv1.goBack(); }); top.setOnClickListener(v -> { Constants.goTop(wv1); }); return mView; } public void setValue(int progress) { this.progress.setProgress(progress); } public class myWebClient extends WebViewClient { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { // TODO Auto-generated method stub super.onPageStarted(view, url, favicon); } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { // TODO Auto-generated method stub System.out.println("when you click on any interlink on webview that time you got url :-" + url); // view.loadUrl(url); return false; } @Override public void onPageFinished(WebView view, String url) { System.out.println("your current url when webpage loading.. finish" + url); super.onPageFinished(view, url); } } }