0

The first part works fine, this means the WKWebview object is able to call the java script function. The problem lies in the javascript code, I assume.

The javascript function, which is called, is supposed to read simply out of a text file in the app's bundle (fileName = "data.txt"). It looks like this:

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()  

 }

The output is always empty. Now I am sure that rawFile status reaches 4, I checked that. I have replaced the fileName with some make-believe non existent file and the rawfile status still reaches 4. So now I am not even sure whether the file has been found.

  1. Is there a way to determine whether the file was found?
  2. If it is found how can I read out of it?

I am not an experienced java script developer at all. So it might be some obvious problem. The javascript function I wrote with help of w3schools.com.

Thanks.

1 Answer 1

1

I think you have some formatting issues with your code and you aren't adding an event listener. Try the below. Also there is better documentation at MDN https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

function readTextFile() {
  document.getElementById("demo").innerHTML = this.responseText;
}
function getTextFile(file) {
  var req = new XMLHttpRequest();
  req.addEventListener("load", readTextFile)
  req.open("GET", file, true)
  req.send();
)

getTextFile('example.txt')
<div id="demo">
</div>

Sign up to request clarification or add additional context in comments.

2 Comments

Since the request is asynchron, it makes sense to add a listener, thanks I did not know how to implement this. It is not quite working yet, for the function readTextfile() is not called. There might be something else missing...
If the text file is placed in the apps bundle the function readTextFile is not called. Though if the text file is located on a remote webserver it is called. I eventually found out that the problem lies in that cross origin requests are only supported for HTTP. This is apperently to due security restrictions... I will try to look for a work around...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.