enClose.js
Functions
enClose.js
is a lightweight JavaScript library that provides two essential functions for Swift-JavaScript communication:
- enClose - Calls native Swift functions from JavaScript with support for data passing and callbacks
- enCloseEvent - Dispatches custom events from Swift to JavaScript
Installation
Include the enClose.js
file in your HTML application:
INFO
This code assumes enClose js is located in your projects www/assets/js
folder.
html
<!DOCTYPE html>
<html>
<head>
<!-- head content -->
</head>
<body>
<!-- body content -->
<script src="assets/js/enClose.js"></script>
</body>
</html>
enClose
Function Syntax
javascript
enClose(nativeCall, data, successCallback, errorCallback);
Parameters
Parameter | Type | Required | Description |
---|---|---|---|
nativeCall | String | Yes | Name of the native Swift method to call |
data | Object | No | Object containing arguments to pass to the Swift method |
successCallback | String | No | Name of the JavaScript function to execute upon successful completion |
errorCallback | String | No | Name of the JavaScript function to execute if an error occurs |
Example Usage
javascript
enClose(
nativeCall: 'processUserData',
data: {
foo: 123,
bar: 'hello'
},
successCallback: 'handleSuccess',
errorCallback: 'handleError'
);
enCloseEvent
Function Syntax
javascript
enCloseEvent(eventName, data);
Parameters
Parameter | Type | Required | Description |
---|---|---|---|
eventName | String | Yes | Name of the custom event to be dispatched |
data | Object | No | Object containing the custom event details |
Example Usage
Dispatching event from Swift side:
swift
evaluateJavascript(javaScript: """
enCloseEvent('someEventHappened');
"""
)
Consuming event in JavaScript:
javascript
document.addEventListener('someEventHappened', function (event) {
alert('Some event happened!');
});
TIP
The framework uses this mechanism to dispatch events when an external display is connected and can be leveraged by your code to send custom events from Swift to JavaScript.