getting a value from webview after form submit

Hi all,

I've got a webview running in my iOS app that loads a html form from a remote sever and returns a value I need for my app after a successful POST submission. The returned value is stored in a javascript variable inside the webview and I'd like to get that value back into the native app.

I believe I need to use evalJS to accomplish this but I'm not sure how to invoke it at the correct time. I don't think I want addEventListener onLoad as that would return an empty variable because the user hasn't filled out the form yet.

This is probably something thats been done a few times but I couldn't find the answer in the QA.

2 Answers

  • Accepted Answer

    what I would do is fire an event from the webView on the form submission.

    as the payload of the event, send back the form data to the application

    — answered 4 years ago by Aaron Saunders
    • Thanks Aaron, sorry to be thick but could you maybe give a bit more detail on that solution? Just to provide a bit more detail, what's actually happening with this form submit is that it's running through a php oauth procedure and returning an access token that I want to capture and store.

      — commented 4 years ago by Russell Morgan
    • how is the access token returned? you can listen to for the onload event of the webview and parse the html response looking for the token.

      — commented 4 years ago by Aaron Saunders
    • Right now it's sitting in a span element with an ID so it's easy to grab the innerHTML value. So if I understand everything correctly I set an evalJS to watch for a function that's tied to the onload event on the page that returns the token?

      — commented 4 years ago by Russell Morgan
    • in the load event of the webView, you are given access to the html content, scan it there looking for the token.

      webView.addEventListener('load', function(e){
          var html = e.source.html
          // look for the token here

      — commented 4 years ago by Aaron Saunders
    • That did the trick Aaron, thanks for leading me down the right path!

      — commented 4 years ago by Russell Morgan
    • I don't believe this answer will work for remote files.

      — commented 4 years ago by Steven Day
    • To clarify, the original answer won't work with remote files. The solution provided in the comments is the only option I've seen discussed without performing another round trip to the server to get the value.

      — commented 4 years ago by Steven Day
  • I didn't think it work remotely either but it did. I think because the initial content in the webview was local that helped. It seems to fire every time there's a load event in that view, perfect for my situation.