The error message "E/Web Console(8272): Uncaught ReferenceError: functionName is not defined:1" popped up when trying to load web views within a

I'm working on incorporating webviews into a view pager.

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = null;      
    v = inflater.inflate(R.layout.webview_layout, container, false);
    myWebView = (WebView)v.findViewById(R.id.webview1);
    WebSettings webSettings = myWebView.getSettings();      
    webSettings.setJavaScriptEnabled(true);
    webSettings.setAppCacheEnabled(true);
    webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
    myWebView.loadUrl("file:///android_asset/web/index.html");
    myWebView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            myWebView.loadUrl("javascript:testFunction()");
        }
    }
}

After the page loads, a javascript function is triggered in onPageFinished(). While scrolling at a regular pace, the web pages load and the Javascript runs smoothly.

However, when scrolling rapidly, the following exception occurs:

> 09-06 14:29:06.750: E/Web Console(8272): Uncaught ReferenceError:
> testFunction is not defined:1

The testFunction() looks like this:

function testFunction(){
    console.log("TestFuntion");     
}

I would appreciate any assistance...

Answer №1

I found a solution to this issue

Simply set the webChromeClient and handle the error by reloading the page...

    myWebView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            isLoading = true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            myWebView.loadUrl("javascript:testFunction()");
        }
    });

    myWebView.setWebChromeClient(new WebChromeClient() {
        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            MessageLevel level = consoleMessage.messageLevel();
            if(level.ordinal() == 3) { // Error ordinal
                if(loading) {
                    myWebView.stopLoading();
                    myWebView.loadUrl(AppConstants.ARTICLE_PAGE_URL);
                }
            }
        }
        return false;
    }

Answer №2

Here's a sample code snippet that you can modify to suit your needs:

Webview Code:

web.getSettings().setJavaScriptEnabled(true);
JavaScriptInterface JSInterface = new JavaScriptInterface(this);
web.addJavascriptInterface(JSInterface, "JSInterface");
setContentView(web);
web.loadUrl("file:///android_asset/demo.html");

Javascript Interface:

public class JavaScriptInterface {
    Context mContext;

    /** Instantiate the interface and set the context */
    JavaScriptInterface(Context c) {
        mContext = c;
    }

    public void showToast() {
        Toast.makeText(mContext, "Button Clicked", Toast.LENGTH_SHORT).show();
    }
}

Webpage Code:

<!DOCTYPE html>
<html>
  <head>
   <script>
     var i=0;
     function myFunction()
     {
       JSInterface.showToast();
     }
   </script>
 </head>

 <body>
    <button onclick="myFunction()">Try it</button>
    <p>By clicking the button above, a function will be called. The function will alert a message.</p>
 </body>
</html>

EDIT

function myFunction()
{
   // Add your custom code here
}

Answer №3

When I encountered the issue of getting an error message saying "Uncaught Reference Error: JavascriptInterfaceName is not defined" every second time I started my hybrid application on versions 4.3 and below, I found a solution with help from @Abi by implementing the following code in my WebChromeClient class:

@Override
@SuppressLint({"AddJavascriptInterface", "InflateParams"})
public boolean onConsoleMessage(@NonNull ConsoleMessage consoleMessage) {
    if("Uncaught ReferenceError: JavascriptInterfaceName is not defined".equals(consoleMessage.message())) {
        webView.addJavascriptInterface(new WebAppInterface(), "JavascriptInterfaceName ");
        webView.reload();
    }
    return super.onConsoleMessage(consoleMessage);
}

After making this change, the issue was resolved! Many thanks for your assistance!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using the jQuery Ternary Operator in Decision Statements

Can someone guide me on writing this code using a ternary operator in the most concise way possible? const isValuePresent = (jQuery('#product-options-wrapper select').val() || jQuery('#product-options-wrapper input').val()) ? true : fa ...

Modify the anchor text when a malfunction occurs upon clicking

Whenever I click on the link, I am able to retrieve the correct id, but the status changes for all posts instead of just the selected item. Below is the HTML code: <div th:each="p : ${posts}"> <div id="para"> <a style="float: right;" href= ...

Tips for Retrieving a JavaScript Variable's Value in JSP

In my JSP file, I have implemented dynamic rows of textboxes using JavaScript. Now that I have input values into these fields, how can I retrieve those values in my result JSP page? ...

Reverting the box color changes in the opposite order of clicking them using HTML, CSS, and Jquery

As someone new to front end development, I am experimenting with creating multiple boxes using HTML, CSS, and jQuery. My goal is to have the boxes change color to blue when clicked, then revert back to their original color in the reverse order they were cl ...

Unraveling nested JSON Response in Struts 2 jQuery <sj:select> tag - A step-by-step guide

Currently, I am developing a web application that utilizes Struts2 and its jQuery Plugin. The <sj:select> tag in my code below works perfectly when the JSON response is not nested: <s:url id="remoteurl" namespace="/XYZ" action= ...

Does utilizing this.someFunction.bind(this) serve a purpose or is it duplicative

As I analyze someone's code, I stumbled upon the following snippet: this.device_name.changes().onValue(this.changeName.bind(this)) My interpretation so far is that onValue requires a callback function, which in this case is this.changeName.bind(this ...

Checking dynamically if a key-value pair exists in a JSON object

Here is some information that I have: "Vitals":[ { "Bp Systolic":"", "Bp Diastolic":"", "Weight":"", "Height":"", "BMI":"" } ], "Lab":[ { "Lipid_profile":[{ "Total Cholestrol":"", "TRIGLYCERID ...

Enhancing the readability of modals with Angular Dialog Service

I have been utilizing the Angular Dialog Service to create popup forms on my website. The source code for this service can be accessed here: https://github.com/m-e-conroy/angular-dialog-service/blob/master/README.md However, I am experiencing an issue wit ...

What is the best way to incorporate a loader.gif that will continue to display until the image (map) has fully loaded in a PHP

A world map allows users to select regions or continents to view companies/products categorized by country. To enhance loading time, an animated loader.gif can be added. However, the current implementation covers the loader only after the map has fully loa ...

The window.open function is creating a new tab using the specified origin or URL

I have a button within an iframe on the webpage "loclahost:3000". When this button is clicked, it should open a new tab with the URL "www.google.com". However, instead of opening the desired URL, the new tab opens with the following incorrect URL: "http:// ...

Ways to implement a backup plan when making multiple requests using Axios?

Within my application, a comment has the ability to serve as a parent and have various child comments associated with it. When I initiate the deletion of a parent comment, I verify the existence of any child comments. If children are present, I proceed to ...

The power of selenium meets the functionality of Javascript with the webdriver

Encountering an issue with Selenium JS Components are created in JSON format as follows: "usernameInputField": { "selector": { "xpath": "//*[@id='username']" } } For invoking webdriver, the following is used: var webdriver = ...

Error Encountered - Configuring Node.js Deployment on the Heroku Platform

"APPLICATION ERROR - Oops! Looks like something went wrong with the application and we couldn't load your page. Please give it another shot in a little while. If you are the app owner, make sure to review your logs for more information." Hey there - ...

Despite calling this.setState to update my state, the render() method is still displaying the previous values

class EditLocation extends Component { constructor(props) { super(); this.state = { LocationId: '', locationOptions: [], } this.baseState = this.state; this.findLocationById = this ...

Is it possible to use Koajs without needing to include the --harmony tag?

Following the merge of iojs into Node, I assumed that I could run koajs without the need for the --harmony tag (as it would have support for generators from es6). Inside my server.js file, I have the following code: var koa = require('koa'); va ...

When using Mongoose paginate, there is always one missing document

I currently have a database with 6 documents and the following route: router.get('', async (req, res) => { const search = req.query.search !=null ? req.query.search : ""; const page = req.query.page !=null ? req.query.page : 1; const limit = ...

JQuery requests functioning flawlessly on one system while encountering issues on other systems

I've encountered an issue with the code on my admin page. It used to work perfectly fine on my system, but now it seems to have stopped functioning. My client urgently needs to update this page, however, when I attempt to run it, the JQuery requests a ...

How to handle an unexpected keyword 'true' error when using the `useState` hook in React?

Trying to set the open prop of the MUIDrawer component to true on user click is causing an error stating "Unexpected keyword 'true'" import React, { useState } from "react"; import { withRouter } from "react-router-dom"; impo ...

Stop GIFs from playing automatically

Looking for a solution to disable autoplay for animated gifs on my chat-site (php-based). Tried script below but out of ideas: <script> myVid=document.getElementsByTagName('img'); function disableAutoplay() { myVid.autoplay=false; m ...

Incorporating Framer Motion into traditional React class components (non-functional approach)

I'm encountering an issue with a simple animation using Framer Motion that functions correctly in a functional component, but fails to work in a class component. I am new to Framer Motion and here is my react code => import {motion} from 'fr ...