Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Webview is not executing my JavaScript from the web page on Android? #14754

Closed
andrisole92 opened this issue Jun 27, 2017 · 48 comments
Closed

Webview is not executing my JavaScript from the web page on Android? #14754

andrisole92 opened this issue Jun 27, 2017 · 48 comments
Labels
Component: WebView Related to the WebView component. Platform: Android Android applications. Ran Commands One of our bots successfully processed a command. Resolution: Locked This issue was locked by the bot.

Comments

@andrisole92
Copy link

andrisole92 commented Jun 27, 2017

Description

When I open WebView on Android emulator or real device it does not execute JavaScript. I have run simple Android App in Android Studio and it worked there.

Reproduction Steps

Just create a new app and add this WebView to it

Sample Code

<WebView
                style={[styles.flex]} //styles
                javaScriptEnabled={true} //enabling JavaScript
                source={{uri: 'http://partners.zeew.eu/'}} //Url
            />

Solution

Can you please check it and say what is wrong?

Additional Information

  • React Native version: 0.45.1
  • Platform: Android ( not sure about iOS )
  • Development Operating System: Windows
  • Build tools: Android Studio: Nexus 5x edited_api_25 Android 6.0 Google APIs, Nexus 5 API level 26, Android 8.0.0
@hramos
Copy link
Contributor

hramos commented Jun 27, 2017

Can you reproduce this using Snack?

@andrisole92
Copy link
Author

andrisole92 commented Jun 27, 2017

Yes: https://snack.expo.io/H18CZMeVW
You may want to check WebView URL in the browser and see when the button in clicked it goes interactive: http://partners.zeew.eu/

But in WebView, when I click a button nothing happens. Same thing with my second website, where the entire page does not load, because it is all in JavaScript.

@hramos
Copy link
Contributor

hramos commented Jun 27, 2017

Any chance you can write a minimal reproduction? Such as loading a very simple website with minimal JavaScript, as opposed to your actual app.

@andrisole92
Copy link
Author

I am using React-navigation (https://reactnavigation.org/), that's why I can't reproduce it fully.
There are two buttons in my app: Login and Register.
When I click on Register, there is a function, that navigates me to the Screen with the WebView, identical to one that I have posted above on Snack.

@andrisole92
Copy link
Author

andrisole92 commented Jun 27, 2017

Anyway, a simple page with only a WebView should be displaying JavaScript with javaScriptEnabled option, right? And it is not.

@UtenteBello
Copy link

I have added a html template into react native webView, but when i run the app on IPad don't work the css files linked on html template.

@UtenteBello
Copy link

Can you help me?

@andrisole92
Copy link
Author

Can you show me your code?

@UtenteBello
Copy link

import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
WebView,
} from 'react-native';

export default class Products extends Component {
render() {
return (
<WebView
source={require('./Prova.html')}
/>
);
}
}

AppRegistry.registerComponent('Products', () => Products);

@UtenteBello
Copy link

This is my index.ios, and Prova.html is a simple file liked to css file

@pankaj-ag
Copy link

pankaj-ag commented Jul 4, 2017

I am having the same issue.

@andrisole92
Copy link
Author

That is why I stopped using React-Native tbh

@andrisole92
Copy link
Author

The community does not seem to be really strong and supportive.

@charpeni
Copy link
Contributor

charpeni commented Jul 5, 2017

Hi @andrisole92,

I'm sorry that you're experiencing some issues with WebView.

Let's figure it out together.

setJavaScriptEnabled from ReactWebViewManager.java seems fine.
defaultProps are set in WebView.android.js.
javaScriptEnabled prop is passed in WebView.android.js.

Could be related to #14834, @koenpunt ?

Does anyone have an idea? If not, I'll try to take a look.

Feel free to ping me if you need any assistance.

@koenpunt
Copy link
Contributor

koenpunt commented Jul 5, 2017

For me the page loaded in the webview has no problem using JavaScript, but the injected JavaScript doesn't get executed without javaScriptEnabled set to true

@pankaj-ag
Copy link

pankaj-ag commented Jul 6, 2017

somehow its not working in android emulator but its working fine in my device.

@ishita-kothari
Copy link

ishita-kothari commented Jul 25, 2017

I am trying to attach html file in webview. the html file contains css and js files as in regular webpages. I am trying to open webView after navigation. Code for WebView is:

const html = require( '../path/index.html')

               <WebView source={html}
                                 style={{height: 700}}
                        />

With this code I am unable to run js on my app. I have also tried javaScriptEnabled to true, but no luck. Also when I build app, it shows me blank page instead of html content.

please help me resolve conflict.

@pankaj-ag
Copy link

pankaj-ag commented Jul 25, 2017

May be this will help -
https://stackoverflow.com/questions/35451139/react-native-webview-not-loading-any-url-react-native-web-view-not-working

@ishita-kothari
Copy link

@pankaj-ag I have tried all the possible ways.

I have local html file placed in android/app/src/main/assets/folder/index/html. This html has injected js in it. I am unable to load js. the js file contains my data. app works fine when I add source url of live site, but with local file it doesnot load properly. my data is not loaded. Please provide me solution.

@pankaj-ag
Copy link

@ishita-kothari can you provide the code snippet here of your web view implementation.
I was also having the same problem in my emulator. So can you test your code on actual devices?

@ishita-kothari
Copy link

<!-- google fonts -->
<link href="https://fonts.googleapis.com/css?family=Open+Sans:400,400i,600,700i|PT+Serif:400,400i,700" rel="stylesheet">
<!-- stylesheets -->
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="css/styles.css?v2.1">
<style type="text/css"> .languages{ text-align: center; list-style: none; font-size: 1.1em; padding-top: 1em; } .languages li{ display: inline-block; padding: 0 1em; text-decoration: underline; } .languages a:hover{ opacity: 0.8; cursor: pointer; } .languages a.selected{ color: #cd6b6d; font-weight: bold; } </style>
<div class = "story">
   <div id = "search-container" >
       <input type="text" id="search" placeholder="Start typing to search for an item" autocomplete="off"></input>
       </div>
  <div class="copy-container">
     
      <div class="results">
          <div class="no-results">No results found</div>
      </div>
  </div>

</div>
<script type="text/javascript" src = "./js/bundle.js?v3.3"></script>

this is the html file. bundle.js file contains the data.

@ishita-kothari
Copy link

can anyone tell me how to include <script> tag in webview?

@cgathergood
Copy link

Any updates to this issue? I've ran into a similar issue with inline JS - thanks!

@AbdallaElabd
Copy link

Same here. Even after putting the Javascript directly in the html, it's still not being executed on Android.

@dlikhachev
Copy link

Any updates on this? I'm facing the same problem now.

@a-r-d
Copy link

a-r-d commented Nov 30, 2017

Hey I'm also having a similar problem. Some of the javascript in my Android webview will fail to execute, but there seems to be no way to get debug information or error messages. Does anyone know how to read the console on the embedded webview? I have resorted to doing stuff like this:

<div id="hello"></div>
<script>
document.getElementById('hello').textContent = "Hello World....";
</script>

Which obviously does not always work because sometimes javascript fails to execute in the webview and I cannot see the console output.

@Jahans3
Copy link

Jahans3 commented Dec 20, 2017

@a-r-d I've done something similar sending a value from a Swift JSContext back into the native layer, it should work the same (in principle) when posting between different JS environment.

I haven't tried running this code but it shouldn't take much to get it to work. The idea is to override console.log so that it instead posts a message back into the RN layer.

injectedJavaScript:

(function () {
  var originalConsoleLog = console.log || window.console.log;
  var patchedConsoleLog = function (message) {
    originalConsoleLog && originalConsoleLog(message);
    window.postMessage && window.postMessage(message);
  };
  console.log = patchedConsoleLog;
})();

handler:

_onMessage = message => {
  console.log(message);
}

WebView:

<WebView onMessage={this._onMessage} />

You may always wish to add an identifier to the patchedConsoleLog so that you can filter messages intended for logging :)

@ggsrivas
Copy link

Javascript execution in webview is not working for android API version 21 and below. Anyone found any solution?

@esutton
Copy link

esutton commented Mar 7, 2018

@pankaj-ag Thank you!

Why does an emulator WebView not work when same emulator's native browser does work?

Try running on a real Android device.

  • On an x86 Android emulator, I can NOT get a WebView to run an external URL that
    returns a webpack ( Angular ) bundle ( Other web pages work fine )
  • The same URL works fine if copied to the x86 Android emulator's native web browser.
  • The same URL works fine running on a WebView on a real Android Device.
  • Other URLs with embedded JS run fine in WebView on emulator.

I am not sure if anything more than javaScriptEnabled is needed.

      render() {
        return (
          <WebView
            source={{ uri: this.props.uri }}
            style={{ marginTop: 0 }}
            scalesPageToFit
            javaScriptEnabled
            domStorageEnabled
            startInLoadingState
            mixedContentMode="always"
          />
        );
      }

@hramos hramos added the Component: WebView Related to the WebView component. label Mar 8, 2018
@react-native-bot react-native-bot added the Ran Commands One of our bots successfully processed a command. label Mar 18, 2018
@react-native-bot react-native-bot added Platform: Android Android applications. Ran Commands One of our bots successfully processed a command. labels Mar 18, 2018
@BSN4
Copy link

BSN4 commented Apr 5, 2018

Confirmed not working on android emulator but works with real device ...

solution : ignore your emulator 💯

@stale
Copy link

stale bot commented Jul 5, 2018

Hey there, it looks like there has been no activity on this issue recently. Has the issue been fixed, or does it still require the community's attention? This issue may be closed if no further activity occurs. You may also label this issue as "For Discussion" or "Good first issue" and I will leave it open. Thank you for your contributions.

@stale stale bot added the Stale There has been a lack of activity on this issue and it may be closed soon. label Jul 5, 2018
@seymoe
Copy link

seymoe commented Jul 28, 2018

@ishita-kothari @cgathergood @abdallamohamed @ggsrivas so there are long time no activity here, did u solved this issue? I just find this and have no idea...

@stale stale bot removed the Stale There has been a lack of activity on this issue and it may be closed soon. label Jul 28, 2018
@ggsrivas
Copy link

In my case, it was a code error. I was using a few es6 syntaxes which were not working on webview in lower android versions (my bad). Luckily I could debug webview javascript in android Lollipop (and above) and that where I found this issue.
Javascript execution in webview has been working fine.

@seymoe
Copy link

seymoe commented Jul 30, 2018

@ggsrivas thx! I have tried and find this problem, too. I used let.. hah

@jamonholmgren
Copy link
Collaborator

This issue has been migrated to react-native-webview/react-native-webview#7 and can be closed here.

@priyankahipoint
Copy link

To enable javascript popups in WebView its necessary to set webChromeClient and override openFileChooser methods.

    mWebview.setWebChromeClient(new WebChromeClient(){
        // For Android 4.1+
        @SuppressWarnings("unused")
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            mUploadMessage = uploadMsg;

            Intent i = new Intent(Intent.ACTION_GET_CONTENT);

            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType(acceptType);

            startActivityForResult(Intent.createChooser(i, "SELECT"), 100);
        }

        // For Android 5.0+
        @SuppressLint("NewApi")
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            if (mUploadMessageArr != null) {
                mUploadMessageArr.onReceiveValue(null);
                mUploadMessageArr = null;
            }

            mUploadMessageArr = filePathCallback;

            Intent intent = fileChooserParams.createIntent();

            try {
                startActivityForResult(intent, 101);
            } catch (ActivityNotFoundException e) {
                mUploadMessageArr = null;

                Toast.makeText(activity,"Some error occurred.", Toast.LENGTH_LONG).show();

                return false;
            }

            return true;
        }
    });

And handle the onActivityResult as below:

@SuppressLint("NewApi")
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 100) {
        if (mUploadMessage == null) return;
        Uri result = data == null || resultCode != Activity.RESULT_OK ? null : data.getData();
        mUploadMessage.onReceiveValue(result);
        mUploadMessage = null;
    }

    else if (requestCode == 101) {
        if (mUploadMessageArr == null) return;
        mUploadMessageArr.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
        mUploadMessageArr = null;
    }

}

@jamonholmgren
Copy link
Collaborator

@priyankahipoint Please update the issue on the other repo. Thanks!

@nikilarigela
Copy link

nikilarigela commented Sep 27, 2018

This issue only comes on old Android devices, It does support ES6 script(It makes sense right).
To work on it just go to babel and parse it.

@jayporta
Copy link

JavaScript isn't executing at all for Android 5.0 and under (<= API 21 as ggsrivas also reported) on the app I'm building as well. Inside the script tag, all I've put is a JavaScript alert and it won't fire. 5.1 and above work (an yes you have to avoid ES6 syntax and use polyfills where necessary).

@nikilarigela
Copy link

@jayporta have u tried with baseUrl=" " baseUrl with empty string.

@ujjwal-sri
Copy link

Is it sure that it js inside the <script> tag of html file won't run on android studio for API level <=21.

@nikilarigela
Copy link

@ujjwal-sri it runs, just you need to write ES5 syntax

@orchuban
Copy link

orchuban commented Nov 5, 2018

I have same problem.
the WebView run script(ES5 only) add css when i run Expo live, bat when i build the apk, i see only HTML without script,link css and file inline.
it's can to kill me!
https://stackoverflow.com/questions/53032302/how-to-path-source-inline-html-in-webview-reactnative-expo

@nikilarigela
Copy link

@orchoban i think you have to mention this in href path asset:/filename

@orchuban
Copy link

orchuban commented Nov 7, 2018

I check it and Expo change the files name of the images and all the files in asset folder.
so I can't get them in src attributes from HTML file(WebView).

@nikilarigela
Copy link

nikilarigela commented Nov 8, 2018

@orchoban I think the best way is to host it and load it with URL rather than loading with local assets.

@SaeedZhiany
Copy link
Contributor

Confirmed not working on android emulator but works with real device ...

solution : ignore your emulator 💯

@if4lcon
I have tested on 3 real android devices and the problem still exists on android 5.1.
Android 7.1.1: works fine
Android 5.1.1: works fine
Android 5.1: not working

also emulators with any android version not working.

@camilo86
Copy link

I'm running an android emulator 7.1.1 and it is working fine, but running on android device 4.4.4 does not work

@facebook facebook locked as resolved and limited conversation to collaborators Dec 11, 2019
@react-native-bot react-native-bot added the Resolution: Locked This issue was locked by the bot. label Dec 11, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Component: WebView Related to the WebView component. Platform: Android Android applications. Ran Commands One of our bots successfully processed a command. Resolution: Locked This issue was locked by the bot.
Projects
None yet
Development

No branches or pull requests