Run JavaScript inside a Web Viewer with App Inventor



With the latest update to our WebViewTools extension, you can now run JavaScript in a Web Viewer in your mobile apps built on App Inventor. You can use this feature to do all sorts of useful things such as prefilling a form for a user.

Activity


Use the following steps to create a sample app which pre fills the Google Search box. In this example, the user will type their search query in the apps text box rather than the Google Search text box. You can also download the sample project at the bottom of this post.

This is the sample test app you will be making.

  1. Download and import the WebViewTools extension into a new App Inventor project.
  2. In your project add a textbox, button, and a Web Viewer to your designer as well as the WebViewTools extension component.
  3. Set the Web Viewer width and height to "Fill Parent" and set the text on the button to "Search"
  4. Switch to the blocks workspace and add a "Screen Initialize" block, Inside this add the "SetWebViewer" block from the WebViewTools extension. (This needs to be set prior to loading a website or the JavaScript won't work.)
  5. Lastly, in the "Screen Initialize" block add the "GoToURL" block from the Web Viewer component and set this to "https://www.google.com.au" Your code should look like this:
  6. Next, add a button click event to your workspace. When the user clicks this button we will insert whatever text the user entered into the Google Search box.
  7. From the WebViewTools component add the code block "RunJavaScript" to the button click event.
  8. The Google Search box has an id of #lst-ib, we will use this in the next step to set the contents of it.
  9. Use a text "Join" block to set the JavaScript code as follows:
    document.getElementById("lst-ib").value="";
  10. Once you have completed that your button click code should look like this:
  11. Now all you need to do is test your app, once you've checked it works, see if you can complete the challenge below.

Challenge


While you can see the example we used isn't the most practical way to use the feature, but it demonstrates its capability. See if you can expand this activity by adjusting the JavaScript to Submit the search query and display the results.

Download project

If you'd prefer to download the example project you can do so here JavaScript_Test.aia

Was this helpful?

Yes No

Thunkable Components