InternetModule
ClassProvides access to the open internet.
- Snapchat: not supported
- SPECS: fully supported
- Camera Kit Web: fully supported
- Camera Kit Mobile: fully supported
- SnapchatNot supported — Available on SPECS and Camera Kit only
- SPECSFully supported
- Camera Kit WebFully supported
- Camera Kit MobileFully supported
Since Lens Scripting v305
Provides access to the open internet. Available only on Spectacles and Camera Kit.
Index
Properties
Methods
Extends
Properties
name
name:
string
The name of the Asset in Lens Studio.
Default Value
""
Inherited from
uniqueIdentifier
readonlyuniqueIdentifier:string
Since
Lens Scripting Version 176
Inherited from
Methods
createWebSocket()
createWebSocket(
url,protocols?,options?):WebSocket
SPECSCamera Kit
The createWebSocket() method initiates a WebSocket connection with the given wss URL and returns a WebSocket object that can be used to send and receive messages from the server.
Syntax
createWebSocket(url)
createWebSocket(url, protocols)
createWebSocket(url, protocols, options)
url Defines the wss URL to which to establish the WebSocket connection.
protocols A protocol string or an array of protocol strings to apply to the WebSocket protocol negotiation.
options Object containing any custom settings you want to apply to the request. See InternetModule#createWebSocketOptions.
Example
//@input Asset.InternetModule internetModule
var internetModule = script.internetModule;
// Create WebSocket connection.
let socket = script.internetModule.createWebSocket("wss://<some-url>");
socket.binaryType = "blob";
// Listen for the open event
socket.onopen = (event) => {
// Socket has opened, send a message back to the server
socket.send("Message 1");
// Try sending a binary message
// (the bytes below spell 'Message 2')
const message = [77, 101, 115, 115, 97, 103, 101, 32, 50];
const bytes = new Uint8Array(message);
socket.send(bytes);
};
// Listen for messages
socket.onmessage = async (event) => {
if (event.data instanceof Blob) {
// Binary frame, can be retrieved as either Uint8Array or string
let bytes = await event.data.bytes();
let text = await event.data.text();
print("Received binary message, printing as text: " + text);
} else {
// Text frame
let text = event.data;
print("Received text message: " + text);
}
});
socket.onclose = (event) => {
if (event.wasClean) {
print("Socket closed cleanly");
} else {
print("Socket closed with error, code: " + event.code);
}
};
socket.onerror = (event) => {
print("Socket error");
};
Parameters
| Parameter | Type |
|---|---|
url | string |
protocols? | string | string[] |
options? | WebSocketOptions |
Returns
Since
Lens Scripting Version 305
createWebSocketOptions()
staticcreateWebSocketOptions():WebSocketOptions
SPECSCamera Kit
Creates a WebSocketOptions instance that can be passed to InternetModule#createWebSocket to configure the connection (for example, to attach custom opening-handshake headers).
Returns
Since
Lens Scripting Version 305
Example
//@input Asset.InternetModule internetModule
const options = InternetModule.createWebSocketOptions();
options.headers = { "Authorization": "Bearer <token>" };
const socket = script.internetModule.createWebSocket(url, undefined, options);
createWebView()
createWebView(
options,onSuccess,onFailure):void
ExperimentalSPECS
This function will create a new instance of a WebView with the specified options. Once it has been created, onSuccess will be invoked, which returns the Texture of the WebView for rendering. This Texture contains a reference to the WebPageTextureProvider through its Control property. WebPageTextureProvider can be used for sending events and actions to the WebView. In the event of an error, the onError callback is invoked with the error message.
Arguments:
- options: The options for a specific WebView.
- onSuccess: Invoked on successful WebView creation. Provides the Asset.Texture for rendering and control.
- onError: Invoked on creation failure. Provides an error message.
Note: Only 1 callback will be invoked, and only once.
Note: After creation, the webview will later invoke onReady on the WebPageTextureProvider.control object to indicate it is ready for handling events and actions.
Creating a Webview Texture in JavaScript:
// Create the options
var resolution = new vec2(512, 512);
var options = InternetModule.createWebViewOptions(resolution);
// Create the WebView
script.internetModule.createWebView(
options,
(texture) => {
script.image.mainPass.baseTex = texture;
webViewControl = texture.control;
webViewControl.onReady.add(() => {
print("onReady");
webViewControl.loadUrl("https://snap.com");
});
},
(msg) => {
print("Error:" + msg);
}
);
Creating a Webview Texture in TypeScript:
const resolution = new vec2(512,512)
const options = InternetModule.createWebViewOptions(resolution)
this.internetModule.createWebView(
options,
(texture: Asset.Texutre) => {
this.image.mainPass.baseTex = texture
this.webViewControl = texture.control
this.webViewControl.onReady.add(() => {
print("onReady")
this.webViewControl.loadUrl("https://snap.com")
})
},
(msg: string) => {
print(`Error: ${msg}`)
}
)
Parameters
| Parameter | Type |
|---|---|
options | WebViewOptions |
onSuccess | (texture) => void |
onFailure | (errorMessage) => void |
Returns
void
Since
Lens Scripting Version 305
createWebViewOptions()
staticcreateWebViewOptions(resolution):WebViewOptions
ExperimentalSPECS
This function creates a WebViewOptions instance that allows you to configure your webview.
Resolution: vec2 type representing the desired webpage resolution.
Note: This is capped at 2048x2048. Note: Once a webview has been created this can not be changed.
Parameters
| Parameter | Type |
|---|---|
resolution | vec2 |
Returns
Since
Lens Scripting Version 305
fetch()
fetch(
request,options?):Promise<Response>
SPECS
The fetch() method starts the process of fetching a resource from the internet, returning a promise that is fulfilled once the response is available.
The promise resolves to a Response object representing the response to your request.
A fetch() promise only rejects in cases of malformed URLs or network errors. A fetch() promise does not reject if the server responds with HTTP status codes that indicate errors. These errors can be checked manually via the Response status properties.
Syntax
fetch(resource)
fetch(resource, options)
resource Defines the URL you wish to fetch, or a Request object.
options Object containing any custom settings you want to apply to the request. Available options are body, method, headers, redirect, and keepalive. For more information on these properties see the Request class. If a Request was given for resource, then these options will entry-wise override the options specified in the Request object.
Example
//@input Asset.InternetModule internetModule
var internetModule = script.internetModule;
// For this example assume this URL simply responds with the same body
// that it receives.
let request = new Request("https://<Your URL>.com", {
method: "POST",
body: JSON.stringify({ user: { name: "user", career: "developer" }}),
headers: {
"Content-Type": "application/json",
},
});
let response = await internetModule.fetch(request, {
body: JSON.stringify({ user: { name: "user", career: "salesman" }})
});
if (response.status != 200) {
print("Failure: response not successful");
return;
}
let contentTypeHeader = response.headers.get("content-type");
if (!contentTypeHeader.includes("application/json")) {
print("Failure: wrong content type in response");
return;
}
let responseJson = await response.json();
let username = responseJson.json["user"]["name"];
let career = responseJson.json["user"]["career"];
print(career); // will print "salesman"
Parameters
| Parameter | Type |
|---|---|
request | string | Request |
options? | any |
Returns
Promise<Response>
Since
Lens Scripting Version 305
getTypeName()
staticgetTypeName():TypeName<InternetModule>
Returns the fully-qualified JavaScript type name for this class (for example, "Component.Camera"). This is a static accessor (no instance required) and returns the same value as the instance getTypeName().
Returns
TypeName<InternetModule>
Since
Lens Scripting Version 305
Overrides
getTypeName()
getTypeName():
string
Returns the name of this object's type.
Returns
string
Inherited from
isOfType()
isOfType(
type):boolean
Returns true if the object matches or derives from the passed in type.
Parameters
| Parameter | Type |
|---|---|
type | string |
Returns
boolean
Inherited from
isSame()
isSame(
other):boolean
Returns true if this object is the same as other. Useful for checking if two references point to the same thing.
Parameters
| Parameter | Type |
|---|---|
other | ScriptObject |
Returns
boolean
Inherited from
makeResourceFromUrl()
makeResourceFromUrl(
mediaUrl):DynamicResource
SPECSCamera Kit
Get a DynamicResource to be used with RemoteMediaModule from mediaUrl.
Parameters
| Parameter | Type |
|---|---|
mediaUrl | string |
Returns
Since
Lens Scripting Version 305
performHttpRequest()
performHttpRequest(
requestOptions,onHttpResponse):void
SPECSCamera Kit
Perform an http request described by RemoteServiceHttpRequest.
The following example demonstrates how to load a Texture using the InternetModule and RemoteMediaModule.
//@input Asset.InternetModule internetModule
//@input Asset.RemoteMediaModule remoteMediaModule
//@input Component.Image image
let request = RemoteServiceHttpRequest.create();
request.url = "https://docs.snap.com/img/spectacles/spectacles-project-info-settings.png";
script.internetModule
.performHttpRequest(request, function(response){
const dynamicResource = response.asResource()
script.remoteMediaModule
.loadResourceAsImageTexture(dynamicResource, function(texture) {
script.image.mainPass.baseTex = texture
},function(error){
print(error)
})
})
Parameters
| Parameter | Type |
|---|---|
requestOptions | RemoteServiceHttpRequest |
onHttpResponse | (response) => void |
Returns
void
Since
Lens Scripting Version 305