Skip to main content
Version: 7.3.1

Native Smartface & WebView Interaction

Using a Hybrid Approach in a Fully Native Environment

Smartface is a fully native development environment with 100% native API access, however, it has a JavaScript based architecture and Smartface applications developed with JavaScript exhibit similarities with Web apps developed via JavaScript. The main difference is that Smartface itself has its own implementation of the UI objects (sf-core) without any use of the DOM which is the basis of the visual portions of the web pages.

Without the DOM support in Smartface due to its native architecture, you cannot use other Web frameworks and libraries such as jQuery or Angular or reactJS. In those cases, Smartface WebView comes in handy, enabling the display of the web content (like a browser) within the App as a component.

Smartface JavaScript engine has its own scope and each WebView has it own scope. They are not interacting to each other directly but there are ways to establish a connection between each other.

In the rest of this guide, WebView component will be used intensively; assuming the reader is knowledgeable about WebView Guide and WebView API Reference.

WebView Code Injection

Smartface WebView instance has a evaluateJS method to run a code block within the displayed Web Page content.

This method takes the script as a string. You cannot pass objects between native app and the WebView directly, as the Smartface app and the Web Page have their own scopes. If you want to pass objects, you can serialize them as JSON and deserialize them on the other side.

Add Smartface Logo to Web Page
const img = document.createElement("img");
img.src = "http://account.smartface.io/Images/logo.png";
document.body.insertBefore(img, document.body.firstChild);

Given code above adds the Smartface logo to the web page, which should be running inside the web page scope.

To run the code in the web page contained in the WebView, following things should be done in order:

  1. Convert your script-to-run to string
    a. The injected code needs to run on document load!
  2. Have your WebView instance set up
  3. After page is loaded, evaluate the script string
Script as String
const script = `
function insertLogo() {
const img = document.createElement("img");
img.src = "http://account.smartface.io/Images/logo.png";
document.body.insertBefore(img, document.body.firstChild);
}
if (document.readyState === "complete")
insertLogo();
else
document.onload = insertLogo();
`;

The sample code given above is for modifying the document.onLoad event. If you are using jQuery you can use document.ready().

WebView Setup and run Script onLoad
import WebView from "@smartface/native/ui/webview";
import FlexLayout from "@smartface/native/ui/flexlayout";

const url = "http://example.com/";
const myWebView = new WebView({
left: 0,
top: 0,
right: 0,
bottom: 0,
positionType: FlexLayout.PositionType.ABSOLUTE,
onShow: (event) => {
console.log(event.url);
if (url === event.url) {
//make sure script is running only on specific url(s)
console.log("about to eval");
myWebView.evaluateJS(script);
}
},
});
this.addChild(myWebView);
myWebView.loadURL(url);
Page Code
import Page1Design from "generated/pages/page1";
import WebView from "@smartface/native/ui/webview";
import FlexLayout from "@smartface/native/ui/flexlayout";
import { Route, Router } from "@smartface/router";

const script = `
function insertLogo() {
const img = document.createElement("img");
img.src = "http://account.smartface.io/Images/logo.png";
document.body.insertBefore(img, document.body.firstChild);
}
if (document.readyState === "complete")
insertLogo();
else
document.onload = insertLogo();
`;

export default class Page1 extends Page1Design {
myWebView: WebView;
constructor(private router?: Router, private route?: Route) {
super({});
}

initWebView() {
const myWebView = new WebView({
left: 0,
top: 0,
right: 0,
bottom: 0,
positionType: FlexLayout.PositionType.ABSOLUTE,
onShow: (event) => {
console.log(event.url);
if (url === event.url) {
//make sure script is running only on specific url(s)
console.log("about to eval");
myWebView.evaluateJS(script);
}
},
});
this.myWebView = myWebView;
this.addChild(myWebView);
}

onShow() {
super.onShow();
const url = "http://example.com/";
this.myWebView.loadURL(url);
}

onLoad() {
super.onLoad();
this.initWebView();
}
}

Using WebView Bridge

WebView Bridge allows bi-directional communication with Web Page. The usages mentioned above, they all are invoked from Native side to Web Page: A JS code is executed and the synchronous response is parsed on the app.
For a press of a button, a timer event, a web socket event on the Web Page can cause an action on the native side. This util library allows event and event data flow to the native side.
In order to trigger an action on the native side, using this WebView Bridge, following code should be executed:

Web Page
//using window variable is recommended
window.boubleEvent("eventName", eventDataObject);

It is possible to add this call to the Web Page from the source of the Web Page (if the developer can access its source code & change it), or it is possible to inject that code from Native using evaluateJS

<html>
<head>
<title>Sample Page</title>
</head>
<body>
<button id="btn">Press me</button>
</body>
</html>

Another approach is to inject that code from native side. There is no need to use them both; use only one of them.

Event Injection
const wvb = (page.wvb = new WebViewBridge({
webView: page.webView,
source: "http://www.google.com",
}));
page.wvb = wvb;

wvb.on("myEvent", () => {
alert("myEvent", "Event fired");
});

wvb.ready().then(() => {
wvb.evaluateJS(script);
});

const script = `
setTimeout(()=> {
window.boubleEvent("myEvent");
}, 1000);
`;

Example Use Cases

  • Display charts or graphics (one way interactions work best for using WebViews in a native app)
  • Logins provided via web (e.g. Oauth Implicit flow)
  • Remove or hide unwanted elements, such as logos from the web page
  • Share authentication
  • Display other components that are on the web that require some data from the app

Hide Elements in a Web Page

In this example, a web page inside WebView is shown and 2 native buttons are added to bottom of the native Smartface page. Those buttons are performing show/hide operations within the web page.

Web Page HTML
<!DOCTYPE html>
<html>
<head>
<title>Smartface - WebView Hide & Show Example </title>
<style type="text/css">
#item {
background-color: RoyalBlue;
color: white;
width: calc(100% - 40px);
height: calc(100% - 40px);
margin: 20px;
display: flex;
align-items: center;
font-size: 72pt;
}

#item div {
width: 100%;
text-align: center;
display: block;
}

html,
body {
height: 100%;
margin: 0;
background-color: DarkSeaGreen;
}
</style>
</head>

<body>
<div id="item">
<div>Item</div>
</div>
</body>

</html>

Link to the web page is also available: https://az793023.vo.msecnd.net/examples/sf-core/webview/hide-show.html

Abstract Smartface code is given below:

Smartface Code
const btnHide = new Button({
onPress: () => {
this.webview1.evaluateJS(
'document.getElementById("item").style.display="none";'
);
},
});

const btnShow = new Button({
onPress: function () {
page.webview1.evaluateJS(
'document.getElementById("item").style.display="flex";'
);
},
});

onShow() {
super.onShow();
this.webview1.loadURL(
"https://az793023.vo.msecnd.net/examples/sf-core/webview/hide-show.html"
);
}
/scripts/pages/pageHideShow.ts
import PageHideShowDesign from "generated/pages/pageHideShow";
import { Route, Router } from "@smartface/router";

export default class PageHideShow extends PageHideShowDesign {
constructor(private router?: Router, private route?: Route) {
super({});
}

initComponents() {
this.btnHide.onPress = () => {
this.webView1.evaluateJS(
'document.getElementById("item").style.display="none";',
() => {}
);
};
this.btnShow.onPress = () => {
this.webView1.evaluateJS(
'document.getElementById("item").style.display="flex";',
() => {}
);
};
}

onShow() {
super.onShow();
this.webView1.loadURL(
"https://az793023.vo.msecnd.net/examples/sf-core/webview/hide-show.html"
);
}

onLoad() {
super.onLoad();
this.headerBar.title = "Hide Show";
this.initComponents();
}
}

Display a chart

In this example, an HTML Chart is shown within the WebView and its data is being modified (set) by the native Smartface code.

Chart example has been taken from Chart.js and slightly modified for demo purposes.
Used sample page is on https://az793023.vo.msecnd.net/examples/sf-core/webview/chart.html

/scripts/pages/pgChart.ts
import PgChartDesign from "generated/pages/pgChart";

export default class PgChart extends PgChartDesign {
constructor(private router?: Router, private route?: Route) {
super({});
}

initComponents() {
this.btnRandomizeData.onPress = () => {
const script = `
config.data.datasets.forEach(function(dataset) {
dataset.data = dataset.data.map(function() {
return randomScalingFactor();
});

});
window.myLine.update();`;
this.webView1.evaluateJS(script, () => {});
};
this.btnAddDataSet.onPress = () => {
const script = `
const colorName = colorNames[config.data.datasets.length % colorNames.length];
const newColor = window.chartColors[colorName];
const newDataset = {
label: 'Dataset ' + config.data.datasets.length,
backgroundColor: newColor,
borderColor: newColor,
data: [],
fill: false
};

for (let index = 0; index < config.data.labels.length; ++index) {
newDataset.data.push(randomScalingFactor());
}

config.data.datasets.push(newDataset);
window.myLine.update();`;
this.webView1.evaluateJS(script, () => {});
};
this.btnRemoveDataset.onPress = () => {
const script = `
config.data.datasets.splice(0, 1);
window.myLine.update();`;
this.webView1.evaluateJS(script, () => {});
};
this.btnAddData.onPress = () => {
const script = `
if (config.data.datasets.length > 0) {
const month = MONTHS[config.data.labels.length % MONTHS.length];
config.data.labels.push(month);

config.data.datasets.forEach(function(dataset) {
dataset.data.push(randomScalingFactor());
});

window.myLine.update();
}`;
this.webView1.evaluateJS(script, () => {});
};
this.btnRemoveData.onPress = () => {
const script = `
config.data.labels.splice(-1, 1); // remove the label first

config.data.datasets.forEach(function(dataset, datasetIndex) {
dataset.data.pop();
});

window.myLine.update();`;
this.webView1.evaluateJS(script, () => {});
};
}

onShow() {
super.onShow();
this.webView1.loadURL(
"https://az793023.vo.msecnd.net/examples/sf-core/webview/chart.html"
);
}

onLoad() {
super.onLoad();
this.initComponents();
}
}

For more information on the Charts, see the following documentation:

Data Charts

Getting button press from WebView

In this example, let's assume the app is displaying some web content, such as an advertisement campaign. The content of the page is displayed, at the end of the document there is a button, such as "I am interested". If user press to the button, the app should capture the press and do something on the native side.

/scripts/pages/webVievBridgeTest.ts
import WebVievBridgeTestDesign from 'generated/pages/webVievBridgeTest';
import { withDismissAndBackButton } from '@smartface/mixins';
import { Route, Router } from '@smartface/router';
import WebViewBridge from '@smartface/webviewbridge';

export default class WebVievBridgeTest extends withDismissAndBackButton(WebVievBridgeTestDesign) {
constructor(private router?: Router, private route?: Route) {
super({});
}
initWebViewBridge() {
try {
const url = 'https://az793023.vo.msecnd.net/examples/webviewbridge/buttonevent.html';
const script = `
const btn = document.getElementById("btn");
btn.onclick = function() {
window.boubleEvent("buttonPress");
};
`;

//Within constructor
const wvb = new WebViewBridge({
webView: this.webView1, //WebView. Should be assigned from UI editor.
source: url
});
wvb.on('buttonPress', (data) => {
const text = 'Button pressed';
console.info(text);
alert(text);
//Do your own logic
});

wvb.ready().then(() => {
wvb.evaluateJS(script);
});
} catch (error) {
console.log(error);
}
}
/**
* @event onShow
* This event is called when the page appears on the screen (everytime).
*/
onShow() {
super.onShow();
this.initBackButton(this.router); //Addes a back button to the page headerbar.
this.webView1.loadURL('https://az793023.vo.msecnd.net/examples/webviewbridge/buttonevent.html');
}

/**
* @event onLoad
* This event is called once when the page is created.
*/
onLoad() {
super.onLoad();
this.initWebViewBridge();
}
}

WebView Bridge - Loading Dynamic Libraries

WebView bridge also allows loading other libraries into the WebView. In the Webviewbridge loadScripts method will be used to perform this action.
This method is adding script tags with src value set to the given URL. This URL should be relative to the page. If it is not relative, absolute URL should be used.
Loading of the scripts are performed after WebView Bridge is ready.
This method also returns a Promise object. This Promise should be used to evaluate scripts which are dependent on the libraries which are loaded with the loadScripts method.

In this example, a cookie string will be injected into the WebView. This cannot be done with JavaScript injection, because the very first initial request should be already authenticated.

Adding Cookie with Native API Access
import System from "@smartface/native/device/system";
const cookie = "Your full cookie";
const targetUrl = "http://example.com";
if (System.OS === System.OSType.IOS) {
//@ts-ignore
const MutableRequest = SF.requireClass("NSMutableURLRequest");
//@ts-ignore
const NSURL = SF.requireClass("NSURL");

const request = MutableRequest.requestWithURL(NSURL.URLWithString(targetUrl));
request.addValueForHTTPHeaderField(`${cookie}`, "Cookie");
webview.nativeObject.load(request); //this is equvalent of webview.loadURL
} else {
//@ts-ignore
const CookieManager = requireClass("android.webkit.CookieManager");
const cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.setCookie(targetUrl, `${cookie}`);
webview.loadURL(targetUrl);
}

evaluateJS Performance

WebView.evaluateJS is used for two things:

  1. To execute a JavaScript on the WebView
  2. Parsing and getting the result of the executed JavaScript statement

Regardless of what both of the steps will be executed. In some cases, the result of the executes JavaScript statement might be too long to parse. This will greatly reduce the performance of the evaluateJS execution.
Simply add a single null statement to the end of the JavaScript statement, this will reduce the parsing of the result operation.
WebViewBridge is designed with that performance trick. Here is the code block from WebView Bridge:

WebView Bridge - evaluateJS
function evaluateJS(javascript, onReceive) {
if (!this.parseResponses)
//a flag used for wrapping the code or not
javascript = `(function(){\n${javascript}\n})();null;`; //Wraps the Code in an immedaite function
return this.webView.evaluateJS(javascript, onReceive);
}