WebView control

Version 1.0 (April 2017)

Requires SCADE Beta3 and higher

Introduction

Many mobile apps need a webView. We wrapped the native webView control from iOS (Wkwebview) and Android (android.webkit.WebView) respectively and access its functionality using one common interface and API. Functionality includes

  • positioning a webView control anywhere within the app page
  • loading a webpage
  • receives events when the page was loaded
  • prevent pages on loading
  • inject and evaluate Javascript

Minimal webView app

  1. Create a new mobile app
  2. Drag and drop the webView onto the page
  3. Add a button
  4. Add this minimal code to reference the webView control in the main.page.swift and load the UIKit page
import ScadeKit

class MainPageAdapter: SCDLatticePageAdapter {

	var webView : SCDWidgetsWebView!
	let webpage = "https://developer.apple.com/reference/webkit/wkwebview"
	
	// page adapter initialization
	override func load(_ path: String) {		
		super.load(path)
		
		self.webView = self.page!.getWidgetByName("webview1") as! SCDWidgetsWebView
		let button1 = self.page!.getWidgetByName("btnLoadPage") as! SCDWidgetsButton
		
		// Add event to load page
		button1.onClick.append(SCDWidgetsEventHandler{ 
			_ in self.webView!.load(self.webpage)
		})
		
		// Add event when page loaded
		self.webView!.onLoaded.append(SCDWidgetsLoadEventHandler{
			(ev:SCDWidgetsLoadEvent?) in print("Page Loaded: \(ev!.url)")})
		
		// Add event when page failed to load
		self.webView!.onLoadFailed.append(SCDWidgetsLoadFailedEventHandler{
			(ev:SCDWidgetsLoadFailedEvent?) in print("Page failed to load \(ev?.message)")})
	}
}

Events on successful and failed load of pages

The SCDWidgetsLoadEvent indicates the successful load of the page and the url indicates the page that we loaded successfully. Similarly, the SCDWidgetsLoadFailedEvent is triggered when a failure occurred.

Controlling if a page should be loaded

In many cases, we want to prevent the loading of some pages based on the URL. This can be done with the SCDWidgetsShouldLoadEventHandler. Return FALSE to indicate that the URL should not be loaded:

// Add handler to control loading of page
self.webView!.onShouldLoad.append(SCDWidgetsShouldLoadEventHandler{
	(ev:SCDWidgetsLoadEvent?) in
		let rtn = !ev!.url.contains("loadhtmlstring")
		print("will load \(ev!.url) : \(rtn)")
    return rtn
 })

Injecting Javascript

The eval function allows you to pass javascript and get the result. In this example, we print the value of the <title> tag:

func getTitle() {
 let javascript = "var x=document.getElementsByTagName(\"title\")[0].text.toString();x"
 let processResult = SCDWidgetsWebViewEvalHandler { result in print(result)}
 let handleException = SCDWidgetsWebViewEvalHandler { error in print(error)}
 // inject javascript
 webView.eval(javascript, onSuccess: processResult, onError: handleException)
}