Toggle navigation
Wialon Playground
Add library
jQuery latest
Bootstrap 3.3.1
Wialon Javascript SDK
Run
Get code
Fork
Save
Examples
Login
Get units
Change unit icon
Get messages
Get sensors
Edit sensors
Commands
Monitoring notification
Track layer
Get resources
Resources and accounts
Account parameters
Do payment
Management Driver
Create notification
Get geofences
Geofence parameters
Create geofence
Gurtam map
Units on map
Unit trace
Create report template
Execute report
Execute custom report
Create driver
Bind driver to unit
Unit edit fields
Import fillings
Token login for site
Advanced authorization form
Token usage in app
Account hierarchy
Nearest units
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Wialon Playground</title> </head> <body> </body> </html>
HTML
.log { margin-bottom: 1em; } .log p { margin: 0; }
CSS
let logEl = document.createElement('div'); logEl.className = 'log'; document.body.appendChild(logEl); logMsg('start'); let pm = new WialonPostMessage({ origin: 'https://hst-api.wialon.com', postHtmlUrl: 'https://hst-api.wialon.com/wialon/post.html', prefix: 'prefix:', }); (async () => { await pm.init(); let response = await pm.request({ path: '/wialon/ajax.html', params: { svc: 'token/login', params: JSON.stringify({ token: '5dce19710a5e26ab8b7b8986cb3c49e58C291791B7F0A7AEB8AFBFCEED7DC03BC48FF5F8', fl: 3, }), }, }); let { error, result } = response; logMsg(`Response got`); if (error) { logMsg(`Error ${error}`); return; } let { eid: sid, user: { nm: userName }, } = result; logMsg(`sid "${sid}", user "${userName}"`); response = await pm.request({ path: '/avl_evts', params: { sid, }, }); if (response.error) { logMsg(`/avl_evts error ${response.error}`); return; } logMsg(`/avl_evts: ${JSON.stringify(response.result)}`); })().catch((error) => { logMsg('uncaught exception', error); }); function logMsg(msg) { let p = document.createElement('p'); p.textContent = msg; logEl.appendChild(p); } function WialonPostMessage(options) { let { prefix, origin, postHtmlUrl } = options; let frame; let messageHandler; let idCounter = 0; let requestsById = new Map(); this.init = async function () { window.addEventListener('message', onMessage); let resolve; let promise = new Promise((_resolve) => { resolve = _resolve; }); messageHandler = function (data) { try { data = JSON.parse(data); } catch (error) { return; } if (!data) { return; } // If there is no `chunkedResult`, // it's old Local, need to non-chunked mode support if (data.id === 0 && !data.error && data.chunkedResult) { resolve(); } }; frame = document.createElement('iframe'); frame.addEventListener('load', () => { logMsg('frame load'); frame.contentWindow.postMessage( JSON.stringify({ id: 0, source: postHtmlUrl, chunkedPrefix: prefix, enableChunkedResult: true, }), '*', ); }); frame.src = postHtmlUrl; document.body.appendChild(frame); await promise; logMsg('post.html initialized'); messageHandler = function (data) { if (typeof data !== 'string') { return; } if (data.slice(0, prefix.length) !== prefix) { return; } // Format: `prefix : id : chunk index : chunks count : chunk data` let colonAfterId = data.indexOf(':', prefix.length); let colonAfterChunkIndex = data.indexOf(':', colonAfterId + 1); let colonAfterChunksCount = data.indexOf( ':', colonAfterChunkIndex + 1, ); let invalid = colonAfterId < 0 || colonAfterChunkIndex < 0 || colonAfterChunksCount < 0; if (invalid) { return; } let id = data.slice(prefix.length, colonAfterId); let chunkIndex = data.slice(colonAfterId + 1, colonAfterChunkIndex); let chunksCount = data.slice( colonAfterChunkIndex + 1, colonAfterChunksCount, ); id = parseInt(id, 10); chunkIndex = parseInt(chunkIndex, 10); chunksCount = parseInt(chunksCount, 10); invalid = !isFinite(id) || !isFinite(chunkIndex) || !isFinite(chunksCount); if (invalid) { return; } if (chunksCount === 1) { onResponse({ id, data: data.slice(colonAfterChunksCount + 1) }); return; } logMsg('TODO: implement multiple chunks response concatenation'); throw new Error('not implemented yet'); }; }; this.request = function ({ path, params }) { idCounter++; let id = idCounter; let encodedParams = Object.entries(params) .map(([key, value]) => { return ( encodeURIComponent(key) + '=' + encodeURIComponent(value) ); }) .join('&'); let resolve; let reject; let promise = new Promise((_resolve, _reject) => { resolve = _resolve; reject = _reject; }); requestsById.set(id, { resolve, reject }); frame.contentWindow.postMessage( JSON.stringify({ id, url: path, params: encodedParams, source: postHtmlUrl, }), '*', ); return promise; }; this.destroy = function () { if (frame && frame.parentNode) { frame.parentNode.removeChild(frame); } window.removeEventListener('message', onMessage); }; function onResponse({ id, data }) { let handler = requestsById.get(id); if (!handler) { return; } try { data = JSON.parse(data); } catch (error) { handler.reject(error); return; } handler.resolve({ error: data.error, result: data.text, }); } function onMessage(event) { if (event.origin !== origin) { return; } if (!event.data) { return; } if (messageHandler) { messageHandler(event.data); } } }
JS
Result
Source code of example
Close ✕
×
Source code