What is the best method for incorporating a JavaScript redirect into an Android WebView?

My issue involves loading a page into a webview. Typically, when I use the code

webview.loadUrl(url);

it functions as expected. The url contains a javascript code that redirects the page. Here is the javascript code:

<script type="text/javascript">
        if (!document.cookie || document.cookie.indexOf('AVPDCAP=') == -1)
        { document.write('<scr'+'ipt src="http://some_link_here+Math.floor(89999999*Math.random()+10000000)+'&millis='+new Date().getTime()+'&referrer='+encodeURIComponent(document.location)+'" type="text/javascript"></scr'+'ipt>'); }
</script>

When attempting to load this javascript code into my webview using the following:

String data = javascript_code_above;
topBannerWV.loadDataWithBaseURL("", data, "text/html", "UTF-8", null);

where 'data' represents the javascript code, the page fails to load. I have also tried the following:

topBannerWV.loadDataWithBaseURL("", data, "text/javascript", "UTF-8", null);

however, this only loads the text into the webview. Can someone provide assistance with this matter?

Thank you.

Answer №1

This is how I have implemented a solution that works flawlessly:

webView.loadUrl("file:///android_asset/html.html");
webView.setWebViewClient(new WebViewClient() {

public void onPageFinished(WebView view, String url) {
    try {           
                webView.loadUrl("javascript:init('" + some parameter + "')");

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
});

The script within the HTML file looks like this:

<script type="text/javascript>
function init(val){
document.getElementById('content').innerHTML=val;
}
window.addEventListener('load',function(){
console.log("Window Loader");
init();
});
</script>

Answer №2

The solution has been found.

Instead of directly passing the string to the webview for loading, I took a different approach by first writing it into a file and then loading that file in the webview.

getContext().getApplicationContext().deleteFile("data.html");
Writer output = null;
File dir = getContext().getApplicationContext().getFilesDir();
File file = new File(dir.getAbsolutePath() + File.separator + "data.html");
file.createNewFile();
output = new BufferedWriter(new FileWriter(file));
output.write(WVdata);
output.close();
topBannerWV.loadUrl("file:///" + getContext().getApplicationContext().getFilesDir() + "/data.html");

It's still unclear to me why this solves the issue, as I am not modifying the data string - just storing it in a file instead.

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

Reading Telnet Data with WCF Service

Currently, I am utilizing an Android smartphone within my application to retrieve GPS data. The GPS data is transmitted via Telnet and my goal is to extract it within the application. Subsequently, I plan to dynamically bind the position of an object, such ...

What is the best way to retrieve and display a well-structured JSON object in a Node

I am currently working on setting up a nodejs server with the following code: var http = require('http'); var port = 1337; http.createServer(function(req, res) { var statusList = { "hasErrors": false, "list" : [ { "id": " ...

Navigating through arrays to access nested objects

Currently, I am attempting to retrieve a specific field within a nested array using the following code: var array1 = []; const data = { [userId]: [{ id: id, name: fullName, email: userEmail }, ], ...

Python does not return the AJAX request back to JavaScript unless JQuery is not utilized

I have set up an XMLHTTPrequest in my javascript code to communicate with a flask location. Here's how I am doing it: var ourRequest = new XMLHttpRequest(); ourRequest.open("GET", "makeDiff") diff = ourRequest.send(); console.log(diff); Once the req ...

Tips on adding a watermark to multi-page PDFs using an image as the watermark

I am currently working on embedding a watermark onto every page of a PDF file using the image-watermark library. So far, I have successfully added a text watermark to files with only one page but now I am exploring ways to extend this functionality for mul ...

Inject the code snippet from CodePen into a WordPress webpage

I have a WordPress page where I want to integrate the HTML, CSS and JS code from my Codepen project. The styling appears to be working correctly, but the JavaScript is not functioning as expected. You can view the page here: Could someone assist me in pr ...

Should I specify each protected route in the middleware file in the matcher for NextJs 14?

Below is the middleware file I've implemented: import { NextResponse } from "next/server"; import { NextRequest } from "next/server"; import { getApiAuth } from "./app/middleware/api/auth"; const validateApi = (req: Requ ...

When clearInterval is used to stop a setInterval, it will not automatically restart if reset with setInterval

I am facing an issue with a countdown timer that I have created using setInterval in JavaScript. The timer is supposed to countdown from one minute at one second intervals. However, when I click the "start" button, it starts the countdown but if I click an ...

Fetching Data Using Asynchronous API Calls

My goal is to retrieve all results consistently from the API, but I am encountering varying outcomes. The for loop seems to be skipping some requests and returning a random number of records. Can anyone provide assistance? I have experimented with using t ...

Can you explain the distinction between document.body.ononline and navigator.onLine?

Can you explain the distinction between document.body.ononline and navigator.onLine? Do they utilize the same JavaScript API for checking network connectivity status (online/offline)? I have searched on Google but couldn't find a definitive answer. If ...

Passport.js simply redirects to the failure page without invoking the LocalStrategy

I'm facing a persistent issue with Passport.js in my Express.js small application. No matter what I input in the LocalStrategy, I always end up being redirected to the failureRedirect without seemingly passing through the LocalStrategy at all. What am ...

Converting an Array with Key-Value pairs to a JSON object using JavaScript

After using JSON.stringify() on an array in JavaScript, the resulting data appears as follows: [ { "typeOfLoan":"Home" }, { "typeOfResidency":"Primary" }, { "downPayment":"5%" }, { "stage":"Just Looki ...

Optimal method for transforming the values of an object or array in JavaScript

I have a group of values that need to be transformed into new values using a legend. The process might sound confusing at first, but it will become clear shortly. To achieve this, I've relied on associative arrays or objects in JavaScript to serve as ...

The functionality of socket.io is not functioning properly on the server, resulting in a 404

I encountered errors while working on a simple socket.io project on my server. The IP address I am using is . All files are stored in public_html and can be accessed through the URL: . Here are the code snippets: <!doctype html> <html> < ...

What is the best way to create a map in React that allows for changing the state without affecting all elements?

When working with a JSON file containing various values, one of them being "iframe" which can hold either "si" (yes) or "no" based on whether it should include an iframe. With this value (yes/no), I need (this.props.tabsiframe === 'yes') to deter ...

Loop through a list of form names using ng-repeat and send each form name to a JavaScript function when clicked

I have multiple forms within an ng-repeat loop, each with a different name. I need to pass the form data when a button inside the form is clicked. However, when I try to call it like this: checkSaveDisable(updateProductSale_{{productIndex}}) it thro ...

In React JS, the data from my response is not being saved into the variable

My goal is to store the response data in the variable activityType. Within the useEffect function, I am iterating over an API based on the tabs value. The API will return a boolean value of either true or false. While I can successfully log these values ...

How can you determine if a string includes all the words listed in a multidimensional array?

I'm brand new to the world of coding but I have a specific goal in mind. Here's an example of the multidimensional array I'm working with: var requiredProducts = [{ product: 'PRODUCT 1', keywords: ['KEYWORD1', & ...

Using React.js to pass data iterated with map function to a modal

I am trying to display my data in a modal when clicking on buttons. The data is currently shown as follows: 1 John watch 2 Karrie watch 3 Karen watch ... like this It is presented in the form of a table with all the 'watch' items being button ...

JQuery drag and drop functionality experiencing issues in Chrome Browser specifically when integrated into a Joomla Article

I recently embedded a jQuery drag and drop example into my Joomla article. Surprisingly, it works perfectly fine on Firefox browser but encounters issues on Chrome. Although the drag and drop functionality works on Chrome, the problem is that the buttons b ...