# Titanium.UI.WebView

The web view allows you to open an HTML5 based view which can load either local or remote content.

Availability
0.8
0.8
9.2.0

# Overview

Use the Titanium.UI.createWebView method or <WebView> Alloy element to create a web view.

Web views are more expensive to create than other native views because of the requirement to load the HTML browser into memory.

The web view content can be any valid web content such as HTML, PDF, SVG or other WebKit supported content types.

# JavaScript Context in WebViews--Local vs. Remote Content

JavaScript in the web view executes in its own context. The web view can interact with this content, but most of this functionality is limited to local content.

Local Scripts

When running local web content (that is, content that is included in the application's resources), scripts have access to the Titanium namespace. In particular, when running local web content:

  • You can use <Titanium.App.addEventListener> and <Titanium.App.fireEvent> to receive and send application-level events.

  • Events can be logged using the Titanium.API logging methods.

Remote Scripts

Scripts downloaded from remote web servers cannot access the Titanium namespace.

To interact with remote content, wait until the content is loaded, then use the Titanium.UI.WebView.evalJS method to execute a JavaScript expression inside the web view and retrieve the value of an expression.

# Local JavaScript Files

During the build process for creating a package, all JavaScript files, that is, any file with a '.js' extension, are removed and their content is encrypted and obfuscated into one resource, causing these files to not load properly in a WebView if they are loaded externally.

For JavaScript files referenced in static local HTML files, these JavaScript files are omitted from processing and left intact, which means they can be correctly loaded in the WebView.

For local JavaScript files not referenced in static local HTML files, for example, a dynamically-generated HTML file referencing a local JavaScript file, rename the file extension of the local JavaScript files to '.jslocal' instead of '.js'.

The build process for testing your application on the simulator, emulator or device does not affect the loading of local JavaScript files.

# iOS Platform Implementation Notes

On the iOS platform, the native web view handles scrolling and other related touch events internally. If you add event listeners on the web view or its parent views for any of the standard touch events (touchstart, click, and so on), these events do not reach the native web view, and the user will not be able to scroll, zoom, click on links, and so on. To prevent this default behavior, set Titanium.UI.WebView.willHandleTouches to false.

In other words, you can have either Titanium-style events against the web view instance, or internal JavaScript events in the DOM, but not both.

# Android Platform Implementation Notes

Android 4.4 and Later Support

Starting with Android 4.4 (API Level 19), the WebView component is based off of Chromium, introducing a number of changes to its rendering engine. Web content may look or behave differently depending on the Android version. The WebView does not have full feature parity with Chrome for Android.

By default, the Chromium WebView uses hardware acceleration, which may cause content to fail to render. If the WebView fails to render the content, the web view will clear itself, displaying only the default background color. The following log messages will be displayed in the console:

[WARN] :   AwContents: nativeOnDraw failed; clearing to background color.
[INFO] :   chromium: [INFO:async_pixel_transfer_manager_android.cc(56)]

To workaround this issue, you can enable software rendering by setting the WebView's borderRadius property to a value greater than zero.

If you are developing local HTML content and size your elements using percentages, the WebView may not calculate the sizes correctly when hardware acceleration is enabled, resulting in the same behavior previously mentioned.

To workaround this issue, you can use the previously mentioned workaround to enable software rendering, use absolute size values or use the onresize (opens new window) event to set the heights of the components. For example, if you have a div element with an id set to component that needs to use the entire web view, the following callback resizes the content to use the full height of the web view:

window.onresize= function(){
    document.getElementById("component").style.height = window.innerHeight + 'px';
};

For more information, see the following topics:

Plugin Support

The Android web view supports native plugins.

To use plugin content, you must set the Titanium.UI.WebView.pluginState property to either Titanium.UI.Android.WEBVIEW_PLUGINS_ON or Titanium.UI.Android.WEBVIEW_PLUGINS_ON_DEMAND.

You must also call Titanium.UI.WebView.pause when the current activity is paused, to prevent plugin content from continuing to run in the background. Call Titanium.UI.WebView.resume when the current activity is resumed. You can do this by adding listeners for the Titanium.Android.Activity.pause and Titanium.Android.Activity.resume events.

Accessing Cookies

On Android, the web view uses the system cookie store which does not share cookies with the Titanium.Network.HTTPClient cookie store. Developers can manage their cookies for both cookie stores using the methods Titanium.Network.addHTTPCookie, Titanium.Network.addSystemCookie, Titanium.Network.getHTTPCookies, Titanium.Network.getHTTPCookiesForDomain, Titanium.Network.getSystemCookies, Titanium.Network.removeHTTPCookie, Titanium.Network.removeHTTPCookiesForDomain, Titanium.Network.removeAllHTTPCookies, Titanium.Network.removeSystemCookie, Titanium.Network.removeAllSystemCookies.

WKWebView

With Titanium SDK 8.0.0, we now use WKWebView to implement Ti.UI.WebView (as Apple has deprecated UIWebView). WKWebView has few restriction specially with local file accessing. For supporting custom-fonts with WKWebView a little modification is required in the HTML files:

<style>
  @font-face
    {
      font-family: 'Lato-Regular';
      src: url('fonts/Lato-Regular.ttf');
    }
</style>

To have a WKWebView scale the page the same way as UIWebView, add the following meta tag to the HTML header:

<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
  </head>
</html>

# Ti.UI.SIZE and WebViews

With Titanium 8.0.0+, Titanium.UI.SIZE does not work for WebViews. We recommend to give a fixed height to Titanium.UI.WebView (as noted in TIDOC-3355 (opens new window)).

As a workaround you can try to get the document.body.scrollHeight inside Titanium.UI.WebView.load event of webview and set the height to webview. See following example.

var win = Ti.UI.createWindow({
  backgroundColor: 'white';
});

var verticalView = Ti.UI.createView({layout: 'vertical', width: "100%", height: "100%"});

verticalView.add(Ti.UI.createLabel({text: 'Label 1', top: 30, width: Ti.UI.SIZE, height: Ti.UI.SIZE}));

var htmla = "<div style='font-family: Helvetica Neue; font-size:16px'><ul><li>Item 1</li><li>Item 2</li></ul></div>";
var html = "<!DOCTYPE html>";

html += "<html><head><meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0'><style type='text/css'>html {-webkit-text-size-adjust: none;}</style><script type='text/javascript'>document.ontouchmove = function(event){event.preventDefault();}</script></head><body style='overflow: hidden'>";
html += htmla;
html += "</body></html>";

var webview = Ti.UI.createWebView({left: '14dp', right: '14dp', top: '7dp', height: Ti.UI.SIZE, html: html, backgroundColor: "yellow"});

verticalView.add(webview);

verticalView.add(Ti.UI.createLabel({text: 'Label 2', top: 30, width: Ti.UI.SIZE, height: Ti.UI.SIZE}));

win.add(verticalView);

win.open();

webview.addEventListener('load', function(e) {
  var result = webview.evalJSSync('document.body.scrollHeight');
  Ti.API.info('webview height: ' + result);
  webview.height = result;
});

# For More Information

See Integrating Web Content (opens new window) in the Titanium Mobile Guides for more information on using web views, including use cases, more code examples, and best practices for web view content.

# Properties

# allowedURLSchemes

Availability
8.0.0
9.2.0
allowedURLSchemes :Array<String>

List of allowed URL schemes for the web view.

See the example section "Usage of allowedURLSchemes and handleurl in iOS".


# allowsBackForwardNavigationGestures

Availability
8.0.0
9.2.0
allowsBackForwardNavigationGestures :Boolean

A Boolean value indicating whether horizontal swipe gestures will trigger back-forward list navigations.

Default: false


# allowsLinkPreview

Availability
5.4.0
9.2.0
allowsLinkPreview :Boolean

A Boolean value that determines whether pressing on a link displays a preview of the destination for the link.

This property is available on devices that support 3D Touch. Default value is false.

If you set this value to true for a web view, users (with devices that support 3D Touch) can preview link destinations, and can preview detected data such as addresses, by pressing on links. Such previews are known to users as peeks. If a user presses deeper, the preview navigates (or pops, in user terminology) to the destination. Because pop navigation switches the user from your app to Safari, it is opt-in, by way of this property, rather default behavior for this class.

Default: false


# assetsDirectory

Availability
9.0.0
9.2.0
assetsDirectory :String

Path of file or directory to allow read access by the WebView.

Use this property to change the resources the web view has access to when loading the content of a local file. By default the web view only has access to files inside the same directory as the loaded file. To reference resources from other directories (e.g. a parent directory) change this property accordingly.

If assetsDirectory references a single file, only that file may be loaded. If assetsDirectory references a directory, files inside that directory may be loaded.

This property needs to be set before url is assigned to a local file.


# blacklistedURLs CREATION ONLYDEPRECATED

Availability
5.4.0
6.1.0
9.2.0
blacklistedURLs :Array<String>

DEPRECATED SINCE 9.2.0

Use the blockedURLs property instead.

An array of url strings to blacklist.

An array of url strings to blacklist. This will stop the webview from going to urls listed in the blacklist. Note, this only applies in the links clicked inside the webview. The first website that is loaded will not be stopped even if it matches the blacklist.


# blockedURLs CREATION ONLY

Availability
9.2.0
9.2.0
9.2.0
blockedURLs :Array<String>

An array of url strings to be blocked.

An array of url strings to be blocked from loading. This will stop the webview from going to urls listed in this array. Note that this only applies to the links tapped on by the end-user. The first website that is loaded will not be stopped, even if it is listed in the blocklist.


# cacheMode

Availability
3.2.0
cacheMode :Number

Determines how a cache is used in this web view.

Default: Titanium.UI.Android.WEBVIEW_LOAD_DEFAULT


# configuration

Availability
8.0.0
9.2.0

The configuration for the new web view.

This property can only be set when creating the webview and will be ignored when set afterwards.


# data

Availability
0.8
0.8
9.2.0

Web content to load.

Android only supports loading data from a Blob, not a File.

See also: url and html.


# disableBounce

Availability
0.8
9.2.0
disableBounce :Boolean

Determines whether the view will bounce when scrolling to the edge of the scrollable region.

Set to true to disable the bounce effect.

Default: false


# disableContextMenu

Availability
6.1.0
6.1.0
9.2.0
disableContextMenu :Boolean

Determines whether or not the webview should not be able to display the context menu.

Set to true to disable the context menu. Note that disabling the context menu will also disable the text selection on iOS.

Default: false


# enableJavascriptInterface CREATION ONLY

Availability
3.6.0
enableJavascriptInterface :Boolean

Enable adding javascript interfaces internally to webview prior to JELLY_BEAN_MR1 (Android 4.2)

This property is introduced to prevent a security issue with older devices (< JELLY_BEAN_MR1)

Default: true


# enableZoomControls

Availability
1.8.0
enableZoomControls :Boolean

If true, zoom controls are enabled.

Default: true


# handlePlatformUrl DEPRECATED

Availability
3.3.0
9.2.0
handlePlatformUrl :Boolean

DEPRECATED SINCE 8.0.0

This property in no more supported in Titanium SDK 8.0.0+. Use property allowedURLSchemes in conjuction with handleurl. See the example section "Usage of allowedURLSchemes and handleurl in iOS".

Lets the webview handle platform supported urls

By default any urls that are not handled by the Titanium platform but can be handled by the shared application are automatically sent to the shared application and the webview does not open these. When this property is set to true the webview will attempt to handle these urls and they will not be sent to the shared application. An example is links to telephone numbers.

Default: undefined. Behaves as if false


# hideLoadIndicator

Availability
3.0.0
9.2.0
hideLoadIndicator :Boolean

Hides activity indicator when loading remote URL.

Default: false


# html

Availability
0.8
0.8
9.2.0
html :String

HTML content of this web view.

See setHtml for additional parameters that can be specified when setting HTML content.

The web view's content can also be set using the data or url properties.

See also: data and url.


# ignoreSslError

Availability
3.0.0
6.0.2
9.2.0
ignoreSslError :Boolean

Controls whether to ignore invalid SSL certificates or not.

If set to true, the web page loads despite having an invalid SSL certificate. If set to false, a web page with an invalid SSL certificate does not load.

iOS Note: As soon as you set this property to true, iOS will cache the response for the lifetime of the current web view.

Default: undefined but behaves as false


# keyboardDisplayRequiresUserAction

Availability
6.1.0
9.2.0
keyboardDisplayRequiresUserAction :Boolean

A Boolean value indicating whether web content can programmatically display the keyboard.

When this property is set to true, the user must explicitly tap the elements in the web view to display the keyboard (or other relevant input view) for that element. When set to false, a focus event on an element causes the input view to be displayed and associated with that element automatically.

Default: undefined but behaves as true


# lightTouchEnabled

Availability
3.2.0
lightTouchEnabled :Boolean

Enables using light touches to make a selection and activate mouseovers.

Setting this property solves the problem of web links with specific length not triggering a link click in Android.

This is only an Android specific property and has no effect starting from API level 18.

This flag is true by default to retain backwards compatibility with previous behavior.

Default: true


# loading

Availability
0.8
9.2.0
loading :Boolean

Indicates if the webview is loading content.


# mixedContentMode CREATION ONLY

Availability
7.5.0
mixedContentMode :Boolean

If true, allows the loading of insecure resources from a secure origin.

On iOS this functionality can be set in the <plist> section of the tiapp.xml using the NSAllowsArbitraryLoads key as part of the App Transport Security. The plist key is enabled by default, allowing arbitrary loads to be processed.

Default: false


# onCreateWindow

Availability
2.1.0
onCreateWindow :Callback<Object>

Callback function called when there is a request for the application to create a new window to host new content.

For example, the request is triggered if a web page wants to open a URL in a new window. By default, Titanium will open a new full-size window to host the new content. Use the callback to override the default behavior.

The callback needs to create a new WebView object to host the content in and add the WebView to the application UI. The callback must return either a WebView object to host the content in or null if it does not wish to handle the request.

The callback is passed a dictionary with two boolean properties:

  • isDialog: set to true if the content should be opened in a dialog window rather than a full-size window.
  • isUserGesture: set to true if the user initiated the request with a gesture, such as tapping a link.

The following example opens new web content in a new tab rather than a new window:

var tabGroup = Ti.UI.createTabGroup(),
    win = Ti.UI.createWindow(),
    tab = Ti.UI.createTab({window: win, title: 'Start Page'}),
    webview = Ti.UI.createWebView({ url:'index.html'});

webview.onCreateWindow = function(e) {
    var newWin = Ti.UI.createWindow(),
        newWebView = Ti.UI.createWebView(),
        newTab = Ti.UI.createTab({window: newWin, title: 'New Page'});
    newWin.add(newWebView);
    tabGroup.addTab(newTab);
    return newWebView;
};

win.add(webview);
tabGroup.addTab(tab);
tabGroup.open();

Availability
7.5.0
7.5.0
9.2.0
onlink :Callback<OnLinkURLResponse>

Fired before navigating to a link.

The callback will be called before navigating to the link. The Boolean return value of the callback will determine if the link will be navigated or discarded.


# overScrollMode

Availability
3.1.0
overScrollMode :Number

Determines the behavior when the user overscrolls the view.

Default: Titanium.UI.Android.OVER_SCROLL_ALWAYS


# pluginState

Availability
1.8.0
pluginState :Number

Determines how to treat content that requires plugins in this web view.

This setting affects the loading of content that requires web plugins.

To enable hardware acceleration, add the tool-api-level and manifest elements shown below inside the android element in your tiapp.xml file.

<android xmlns:android="http://schemas.android.com/apk/res/android">
    <tool-api-level>11</tool-api-level>
    <manifest>
        <application android:hardwareAccelerated="true"/>
    </manifest>
</android>

See Android documentation for WebSettings.PluginState.

This property only works on Android devices at API Level 8 or greater.

Default: Titanium.UI.Android.WEBVIEW_PLUGINS_OFF


# progress READONLY

Availability
9.1.0
8.0.0
9.2.0
progress :Number

An estimate of what fraction of the current navigation has been loaded.

This value ranges from 0.0 to 1.0 based on the total number of bytes expected to be received, including the main document and all of its potential subresources. After loading completes, the progress remains at 1.0 until a new download starts, at which point progress is reset to 0.0.


# requestHeaders

Availability
6.1.0
6.1.0
9.2.0
requestHeaders :Dictionary

Sets extra request headers for this web view to use on subsequent URL requests.

Setting this property allows you to set custom headers to the URL requests. The parameter will be key-value pairs: {"Custom-field1":"value1", "Custom-field2":"value2"}

On Android you should avoid Calling setRequestHeaders() right after createWebView(). Use the requestHeaders property inside createWebView() or put it inside the window open event.


# scalesPageToFit

Availability
0.8
0.8
9.2.0
scalesPageToFit :Boolean

If true, scale contents to fit the web view.

On iOS, setting this to true sets the initial zoom level to show the entire page, and enables the user to zoom the web view in and out. Setting this to false prevents the user from zooming the web view.

On Android, only controls the initial zoom level.

Default: `false` on iOS. On Android, `false` when content is specified as a local URL, `true` for any other kind of content (remote URL, `Blob`, or `File`).


# scrollsToTop

Availability
2.0.0
9.2.0
scrollsToTop :Boolean

Controls whether the scroll-to-top gesture is effective.

The scroll-to-top gesture is a tap on the status bar; The default value of this property is true. This gesture works when you have a single visible web view. If there are multiple table views, web views, text areas, and/or scroll views visible, you will need to disable (set to false) on the above views you DON'T want this behaviour on. The remaining view will then respond to scroll-to-top gesture.

Default: true


# secure READONLY

Availability
8.0.0
9.2.0
secure :Boolean

A Boolean value indicating whether all resources on the page have been loaded through securely encrypted connections.


# selectionGranularity READONLY

Availability
8.0.0
9.2.0
selectionGranularity :Number

The level of granularity with which the user can interactively select content in the web view.


# timeout

Availability
8.0.0
9.2.0
timeout :Number

The timeout interval for the request, in seconds.


# title READONLY

Availability
8.0.0
9.2.0
title :String

Returns page title of webpage.


# url

Availability
0.8
0.8
9.2.0
url :String

URL to the web document.

This property changes as the content of the webview changes (such as when the user clicks a hyperlink inside the web view).

See also: data and html.


# userAgent

Availability
2.0.0
6.1.0
9.2.0
userAgent :String

The User-Agent header used by the web view when requesting content.

On the iOS platform, this is not per-webview. Once you have set this property for a webview it will not change for same. But while creating new webview it can be changed to new user agent.

On Android, changing the user agent after the webview has begun loading content may cause the webview to reload and fire multiple load or beforeload events. Developers should provide the user agent value in the creation properties to avoid the reload and multiple events firing.

Default: System default user-agent value.


# willHandleTouches

Availability
1.8.2
9.2.0
willHandleTouches :Boolean

Explicitly specifies if this web view handles touches.

On the iOS platform, if this web view or any of its parent views have touch listeners, the Titanium component intercepts all touch events. This prevents the user from interacting with the native web view components.

Set this flag to false to disable the default behavior. Setting this property to false allows the user to interact with the native web view and still honor any touch events sent to its parents. No touch events will be generated when the user interacts with the web view itself.

Set this flag to true if you want to receive touch events from the web view and the user does not need to interact with the web content directly.

This flag is true by default to retain backwards compatibility with previous behavior.

Default: true


# zoomLevel

Availability
7.3.0
7.3.0
9.2.0
zoomLevel :Number

Manage the zoom-level of the current page.

Default: undefined. Behaves as no zoom applied.

# Methods

# addScriptMessageHandler

Availability
8.0.0
9.2.0
addScriptMessageHandler(handlerName) → void

Adds a script message handler.

Adding a script message handler with name 'name' causes the JavaScript function window.webkit.messageHandlers.name.postMessage(messageBody) to be defined in all frames in the web view.

Parameters

Name Type Description
handlerName String

The name of the message handler and should not be 'Ti', as titanium is using it for internal usage.

Returns

Type
void

# addUserScript

Availability
8.0.0
9.2.0
addUserScript(params) → void

Adds a user script.

Parameters

Name Type Description
params UserScriptParams

Properties required to create user script.

Returns

Type
void

# backForwardList

Availability
8.0.0
9.2.0
backForwardList() → BackForwardList

An object which maintains a list of visited pages used to go back and forward to the most recent page.

Returns


# canGoBack

Availability
0.8
0.8
9.2.0
canGoBack() → Boolean

Returns true if the web view can go back in its history list.

Returns

Type
Boolean

# canGoForward

Availability
0.8
0.8
9.2.0
canGoForward() → Boolean

Returns true if the web view can go forward in its history list.

Returns

Type
Boolean

# createPDF

Availability
9.2.0
createPDF(callback) → void

Create a PDF document representation from the web page currently displayed in the WebView.

If the data is written to a file the resulting file is a valid PDF document.

Parameters

Name Type Description
callback Callback<DataCreationResult>

Function to call upon pdf creation.

Returns

Type
void

# createWebArchive

Availability
9.2.0
createWebArchive(callback) → void

Create WebKit web archive data representing the current web content of the WebView.

WebKit web archive data represents a snapshot of web content. It can be loaded into a WebView directly, and saved to a file for later use.

Parameters

Name Type Description
callback Callback<DataCreationResult>

Function to call upon web archive creation.

Returns

Type
void

# evalJS

Availability
0.8
0.8
9.2.0
evalJS(code[, callback]) → String

Evaluates a JavaScript expression inside the context of the web view and optionally, returns a result. If a callback function is passed in as second argument, the evaluation will take place asynchronously and the the callback function will be called with the result.

The JavaScript expression must be passed in as a string. If you are passing in any objects, you must serialize them to strings using Global.

The evalJS method returns a string representing the value of the expression. For example, the following call retrieves the document.title element from the document currently loaded into the web view.

var docTitle = myWebView.evalJS('document.title');

It is not necessary to include return in the JavaScript. In fact, the following call returns the empty string:

myWebView.evalJS('return document.title');

The evalJS variant with a second callback argument executes asynchronously.

myWebView.evalJS('document.title', function (result) {
  // Manipulate the result here
});

Parameters

Name Type Description
code String

JavaScript code as a string. The code will be evaluated inside the web view context.

callback Callback<String>

Optional callback function for the result. Required on Windows, optional on iOS/Android.

Returns

Result of the evaluation. May be null if the asynchronous variant of this method is called.

Type
String

# findString

Availability
9.2.0
findString(searchString[, options, callback]) → void

Searches the page contents for the given string.

Parameters

Name Type Description
searchString String

The string to search for.

options StringSearchOptions

Options for search.

callback Callback<SearchResult>

Function to call upon search finished.

Returns

Type
void

# goBack

Availability
0.8
0.8
9.2.0
goBack() → void

Goes back one entry in the web view's history list, to the previous page.

Returns

Type
void

# goForward

Availability
0.8
0.8
9.2.0
goForward() → void

Goes forward one entry in this web view's history list, if possible.

Returns

Type
void

# pause

Availability
1.8.0
pause() → void

Pauses native webview plugins.

Add a pause handler to your Titanium.Android.Activity and invoke this method to pause native plugins.

Call resume to unpause native plugins.

Returns

Type
void

# release

Availability
2.0.0
release() → void

Releases memory when the web view is no longer needed.

Returns

Type
void

# reload

Availability
0.8
0.8
9.2.0
reload() → void

Reloads the current webpage.

Returns

Type
void

# removeAllUserScripts

Availability
8.0.0
9.2.0
removeAllUserScripts() → void

Removes all associated user scripts.

Returns

Type
void

# removeScriptMessageHandler

Availability
8.0.0
9.2.0
removeScriptMessageHandler(name) → void

Removes a script message handler.

Parameters

Name Type Description
name String

The name of the message handler.

Returns

Type
void

# repaint

Availability
0.8
9.2.0
repaint() → void

Forces the web view to repaint its contents.

Returns

Type
void

# resume

Availability
1.8.0
resume() → void

Resume native webview plugins.

Used to unpause native plugins after calling pause.

Add a resume handler to your Titanium.Android.Activity and invoke this method to resume native plugins.

Returns

Type
void

# setBasicAuthentication

Availability
0.8
0.8
9.2.0
setBasicAuthentication(username, password, persistence) → void

Sets the basic authentication for this web view to use on subsequent URL requests.

The persistence property of this method is only supported on iOS and Titanium SDK 8.0.0+. It is ignored on other platforms and versions.

Parameters

Name Type Description
username String

Basic auth user name.

password String

Basic auth password.

persistence Number

Constants specify how long the credential will be kept. This is only supported on iOS and Titanium SDK 8.0.0+.

Returns

Type
void

# setHtml

Availability
8.1.0
2.0.0
9.2.0
setHtml(html[, options]) → void

Sets the value of html property.

The options parameter can be used to specify two options that affect the WebView main content presentation:

  • baseURL. Sets the URL that the web content's paths will be relative to.
  • mimeType. Sets the MIME type for the content. Defaults to "text/html" if not specified.

For example:

setHtml('<html><body>Hello, <a href="/documentation">Titanium</a>!</body></html>',
        { baseURL: 'https://developer.appcelerator.com/' });

Parameters

Name Type Description
html String

New HTML to display in the web view.

options setHtmlOptions

Optional parameters for the content. Only used by iOS and Android.

Returns

Type
void

# startListeningToProperties

Availability
8.0.0
9.2.0
startListeningToProperties(propertyList) → void

Add native properties for observing for change.

Some common properties are title, URL, estimatedProgress etc. See native KVO capability at https://developer.apple.com/documentation/webkit/wkwebview. See example section "Listening to Web View properties in iOS" for usage.

Parameters

Name Type Description
propertyList Array<String>

List of properties for listen.

Returns

Type
void

# stopListeningToProperties

Availability
8.0.0
9.2.0
stopListeningToProperties(propertyList) → void

Remove native properties from observing.

Parameters

Name Type Description
propertyList Array<String>

List of properties to remove.

Returns

Type
void

# stopLoading

Availability
0.8
0.8
9.2.0
stopLoading() → void

Stops loading a currently loading page.

Returns

Type
void

# takeSnapshot

Availability
8.0.0
9.2.0
takeSnapshot(callback) → void

Takes a snapshot of the view's visible viewport.

Parameters

Name Type Description
callback Callback<SnapshotResult>

Function to call upon snapshot captured.

Returns

Type
void

# Events

# beforeload

Availability
0.8
0.8
9.2.0

Fired before the web view starts loading its content.

This event may fire multiple times depending on the content or URL. For example, if you set the URL of the web view to a URL that redirects to another URL, such as an HTTP URL redirecting to an HTTPS URL, this event is fired for the original URL and the redirect URL.

This event does not fire when navigating remote web pages.

Properties

Name Type Description
url String

URL of the web document being loaded.

navigationType Number

Constant indicating the user's action.

isMainFrame Boolean

Indicate if the event was generated from the main page or an iframe.

source Object

Source object that fired the event.

type String

Name of the event fired.

bubbles Boolean

True if the event will try to bubble up if possible.

cancelBubble Boolean

Set to true to stop the event from bubbling.


# error

Availability
0.8
0.8
9.2.0

Fired when the web view cannot load the content.

The errorCode value refers to one of the Titanium.UI URL_ERROR constants or, if it does not match one of those constants, it refers to a platform-specific constant. The platform-specific values are underlying iOS NSURLError* or Android WebViewClient ERROR_* constants.

Properties

Name Type Description
success Boolean

Indicates a successful operation. Returns false.

error String

Error message, if any returned. May be undefined.

code Number

Error code. If the error was generated by the operating system, that system's error value is used. Otherwise, this value will be -1.

url String

URL of the web document.

message String

Error message. Use error instead.

errorCode Number

A constant or underlying platform specific error code. Use code instead.

source Object

Source object that fired the event.

type String

Name of the event fired.

bubbles Boolean

True if the event will try to bubble up if possible.

cancelBubble Boolean

Set to true to stop the event from bubbling.


# load

Availability
0.8
0.8
9.2.0

Fired when the web view content is loaded.

Properties

Name Type Description
url String

URL of the web document.

source Object

Source object that fired the event.

type String

Name of the event fired.

bubbles Boolean

True if the event will try to bubble up if possible.

cancelBubble Boolean

Set to true to stop the event from bubbling.


# onLoadResource

Availability
3.6.0

Fired when loading resource.

Android only. Notify the host application that the WebView will load the resource specified by the given url.

Properties

Name Type Description
url String

The url of the resource that will load.

source Object

Source object that fired the event.

type String

Name of the event fired.

bubbles Boolean

True if the event will try to bubble up if possible.

cancelBubble Boolean

Set to true to stop the event from bubbling.


# sslerror

Availability
3.3.0
8.0.0
9.2.0

Fired when an SSL error occurred.

This is a synchronous event and the developer can change the value of ignoreSslError to control if the request should proceed or fail.

Properties

Name Type Description
code Number

SSL error code.

source Object

Source object that fired the event.

type String

Name of the event fired.

bubbles Boolean

True if the event will try to bubble up if possible.

cancelBubble Boolean

Set to true to stop the event from bubbling.


# onStopBlacklistedUrl DEPRECATED

Availability
5.4.0

DEPRECATED SINCE 6.1.0

Use the cross-platform blacklisturl event instead.

Fired when a blacklisted URL is stopped.

Properties

Name Type Description
url String

The URL of the web document that is stopped.

source Object

Source object that fired the event.

type String

Name of the event fired.

bubbles Boolean

True if the event will try to bubble up if possible.

cancelBubble Boolean

Set to true to stop the event from bubbling.


# blacklisturl DEPRECATED

Availability
6.1.0
6.1.0
9.2.0

DEPRECATED SINCE 9.2.0

Use the blockedurl event instead.

Fired when a blacklisted URL is stopped.

Properties

Name Type Description
url String

The URL of the web document that is stopped.

source Object

Source object that fired the event.

type String

Name of the event fired.

bubbles Boolean

True if the event will try to bubble up if possible.

cancelBubble Boolean

Set to true to stop the event from bubbling.


# blockedurl

Availability
9.2.0
9.2.0
9.2.0

Fired when a URL has been blocked from loading.

This event is fired when the end-user attempts to navigate to a website matching a URL in the blockedURLs property.

Properties

Name Type Description
url String

The URL of the web document that has been blocked from loading.

source Object

Source object that fired the event.

type String

Name of the event fired.

bubbles Boolean

True if the event will try to bubble up if possible.

cancelBubble Boolean

Set to true to stop the event from bubbling.


# message

Availability
8.0.0
9.2.0

Fired when a script message is received from a webpage.

This event get fired when you have added a message handler using addScriptMessageHandler and the webpage sends a message to it.

Properties

Name Type Description
url String

URL of the web document being loaded.

body String

The body of the message sent from webview.

name String

The name of the message handler to which the message is sent.

isMainFrame Boolean

A Boolean value indicating whether the frame is the web site's main frame or a subframe.

source Object

Source object that fired the event.

type String

Name of the event fired.

bubbles Boolean

True if the event will try to bubble up if possible.

cancelBubble Boolean

Set to true to stop the event from bubbling.


# progress

Availability
9.1.0
8.0.0
9.2.0

Fired when webpage download progresses.

Provides a normalized value between 0.0 and 1.0, where 0.0 indicates nothing was downloaded and 1.0 means the page and all of its resources has finished downloading.

Properties

Name Type Description
value Number

An estimate of what fraction of the current navigation has been loaded.

url String

URL of the web document being loaded.

source Object

Source object that fired the event.

type String

Name of the event fired.

bubbles Boolean

True if the event will try to bubble up if possible.

cancelBubble Boolean

Set to true to stop the event from bubbling.


# redirect

Availability
8.0.0
9.2.0

Fired when a web view receives a server redirect.

Properties

Name Type Description
title String

Page title of webpage.

url String

URL of the web document being loaded.

source Object

Source object that fired the event.

type String

Name of the event fired.

bubbles Boolean

True if the event will try to bubble up if possible.

cancelBubble Boolean

Set to true to stop the event from bubbling.


# handleurl

Availability
8.0.0
9.2.0

Fired when allowedURLSchemes contains scheme of opening url.

See the example section "Usage of allowedURLSchemes and handleurl in iOS".

Properties

Name Type Description
handler String
url String

URL of the web document being loaded.

source Object

Source object that fired the event.

type String

Name of the event fired.

bubbles Boolean

True if the event will try to bubble up if possible.

cancelBubble Boolean

Set to true to stop the event from bubbling.