Executing a JavaScript function using evaluateJavaScript(..) to retrieve information from a text file stored in the application's bundle

The initial part is functioning correctly, indicating that the WKWebview object can successfully call the javascript function. The issue seems to be within the javascript code itself.

The purpose of the javascript function being called is to simply read from a text file located in the app's bundle (fileName = "data.txt"). Here is how it looks:

function readTextFile(fileName)
{
     var rawFile = new XMLHttpRequest();
     rawFile.onreadystatechange = function()
     { 
         if(rawFile.status == 4)
         { 
             document.getElementById("demo").innerHTML = this.responseText;
         }
     }

    rawFile.open("GET",file,true)
    rawFile.send()  

 }

However, the output is consistently empty. Despite confirming that the rawFile status does reach 4, I am now uncertain as to whether the file is actually being found. Even after substituting the fileName with a fictional non-existent file, the rawFile status still reaches 4. This uncertainty leaves me questioning if the file has been located at all.

  1. Is there a method to verify whether the file was indeed located?
  2. If the file is present, how can its contents be successfully read?

I openly admit my lack of expertise in javascript development. Therefore, the root of the problem may be something rather obvious. The creation of the javascript function was done with support from w3schools.com.

Your assistance is greatly appreciated.

Answer №1

It appears there are formatting errors in your code and you may be missing an event listener. Consider the following revised version. For more detailed documentation, refer to MDN here.

function displayText() {
  document.getElementById("content").innerHTML = this.responseText;
}
function fetchText(file) {
  var request = new XMLHttpRequest();
  request.addEventListener("load", displayText)
  request.open("GET", file, true)
  request.send();
)

fetchText('example.txt')
<div id="content">
</div>

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

Creating dynamic and interactive web pages can be achieved by utilizing either $_POST or $_GET with Modal,

In the snippet below, you'll find the HTML code that pulls an array of 6 objects from a database and displays them in a Bootstrap row successfully. <div class="row products"> <?php while($product = mysqli_fetch_assoc($featured)) ...

Adding wrapAll in jQuery or PHP after tags with identical IDs can be achieved by selecting all the target elements

web development <?php foreach ($forlop as $value) : ?> <?php $stringTitle = substr($value->getTitle(), 0, 1); ?> <?php if(is_numeric($stringTitle)){ echo "<h3 id ...

The functionality of Jquery-chosen appears to be malfunctioning when applied to a select element

I am encountering an unusual issue with Jquery-Chosen. There is a multi-select box within a pop-up where the options are populated using an ajax call. Strangely, Jquery-Chosen does not seem to work on it. However, if I use a static multi-select box in the ...

Using specific sections of JSON data to display in an alert message (Vanilla JavaScript)

I am seeking a bookmarklet that, upon clicking, will access JSON data and retrieve the "temp" information to display in an alert indicating the weather with just one click. Is there a method to achieve this or do I need to utilize a different API? Here&ap ...

Tips on showing a specific div when a button is clicked using jQuery and Bootstrap

In my button group, I have four buttons and I need one specific button to display certain div content when clicked. The displayed content should be based on which button is clicked. Is there a way to achieve this using Twitter Bootstrap jQuery in ASP.NET ...

Modifying the default error message in Yup: A step-by-step guide

What is the process for modifying the default error message to a custom error message? Specifically, my custom message. const VALIDATION_SCHEME = Yup.object().shape({ numOne: Yup.Number().required('!'), numTwo: Yup.Number() .r ...

Unable to alter state from the onClick event of a dialog button

In the process of developing a Next.js app, I encountered an interesting challenge within one of the components involving a DropdownMenu that triggers a DialogAlert (both powered by Shadcn components). The issue arises when attempting to manage the dialog& ...

Guide to converting the title into an H2 heading

I am currently working on a page that displays a dynamic title. However, when I attempt to change the title to h2 using HeaderCfg, it wraps the text in a span tag like this: <h2 class=" x-unselectable"> <span class="x-panel-header ...

Is it feasible to utilize UIAlertController on a modal presentation?

A situation has arisen where I have a modal view controller that needs to present an action sheet. However, when I attempt to do so using the following code snippet: UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:nil message: ...

Acquire the Information from a Textarea That Has Been Edited by the User

My challenge lies in taking user-entered text from a content editable textarea and sending it via POST request, but the fields edited by the user are returning with an empty textContent. The code snippet below shows that each .entryRow (obj) contains multi ...

Having trouble showing the information in JavaScript

Here is some code snippet: if(data.error) { msg1.textContent=data.error } else { msg1.textContent=data.location msg2.textContent=data.forecast console.log(data.forecast) } }) Unfortunately, I'm facing an is ...

Creating a function with a flexible number of parameters assigned to a variable:

When setting up a Socket.IO client, I have multiple methods structured like the following: myobject.prototype.A = function (callback) { this.foo('a', null, callback); } myobject.prototype.B = function (bar, callback) { this.foo('b&a ...

Obtain the unique identifiers for each element within an array and attach them to the option values for each item

Forgive me for any misuse of terms, as I am relatively new to Javascript. However, I hope I can describe the desired result effectively in order to receive assistance with my inquiry. Within the code snippet below, there is an array named dates that outpu ...

What is the reason behind the restriction on using capital letters in React project names?

When attempting to create a new project "newRecipeApp" in React, I encountered the following message: npx: installed 91 in 29.359s Could not create a project called "newRecipeApp" because of npm naming restrictions: * name can no longer contain capital ...

Using Selenium together with Mocha/Chai to determine the absence of an item in the DOM and return false

In my current project, I am using selenium-webdriver with Mocha & Chai in a JavaScript environment. I am trying to determine if a user is logged in by checking for the presence of a specific element in the DOM. If the user is logged in, then the following ...

What is the method for configuring a timezone in Selenium Chromedriver?

I'm struggling to set a specific timezone while using Chromedriver. Is there an argument in ChromeOptions that can help with this? The problem arises when I visit certain websites (such as ), where it displays the system time based on Windows setting ...

How to achieve multiplication in Javascript without utilizing the * operand

Challenge 1 Criteria: This problem involves working with two positive integers N and M. Outcome: Upon completion, the function should output the result of multiplying N and M. For instance, if you input 5 and 8 into the function, it should calculate and ...

When making a JavaScript ajax request, Django is not being activated

I'm struggling to implement a feature where the text on a webpage changes based on the selection made in a dropdown menu. My JavaScript code doesn't seem to be calling the Django function correctly, so the placeholder text remains unchanged. Jav ...

Is it the correct method to query names within JavaScript arrays?

I am looking to create a dynamic list view using React JS without relying on any pre-built components. My goal is to incorporate a basic search function that can find users by their names, and I need to address this issue... For example, I have drafted th ...

Divide the promised variable into separate named variables

Here is a code snippet that I am working with: Promise.all( categories.map(category => Collection.find({ category })) ).then(items => { return items }) Currently, the output is an array with the same length as categories, where each element is ...