Network
The runtime has the standard fetch (with Headers, Request, Response, AbortController, AbortSignal) and WebSocket, and XMLHttpRequest (for libraries that still use it, such as howler.js). Reaching http(s) and ws(s) addresses needs the network permission in the manifest; without it fetch fails with a TypeError, XMLHttpRequest fires error, and new WebSocket() throws a SecurityError.
js
async function loadWeather(city) {
const response = await fetch(`https://api.example.com/weather?city=${city}`, {
signal: AbortSignal.timeout(10000),
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
}
const socket = new WebSocket('wss://stream.example.com/ticker');
socket.onmessage = (event) => update(JSON.parse(event.data));
socket.onclose = (event) => setTimeout(reconnect, 5000);- Addresses on the internet must be
https://andwss://: plainhttp://andws://fail as if offline (macOS App Transport Security). They still work withlocalhost, IP addresses and*.localnames, for a development server on your Mac or local network. - Relative addresses (
data.json,./data.json,/data.json) read files in the package, with no permission needed; a missing file is a 404 response.data:andblob:addresses work too. - There is no CORS: every response can be read. Each mini program has cookies of its own, kept in memory only.
fetchreturns as soon as the headers arrive and the body is a stream (response.body, aReadableStream) to read while it downloads; when nothing reads it, the download pauses after buffering about 1 MB.text(),json(),arrayBuffer(),blob()andformData()read the whole body. Like in browsers,text()always decodes UTF-8. The system buffers the first 512 bytes oftext/plainresponses (content sniffing) before handing them over, so services that push text piece by piece (server-sent events, say) should usetext/event-streamor another type.- Request bodies can be strings, bytes (
ArrayBuffer, typed arrays),Blob,FormData(sent as multipart/form-data),URLSearchParamsorReadableStream(withduplex: 'half', as in browsers; it's read to the end before sending, not streamed). - WebSocket binary messages are
Blobs by default, as in browsers; setsocket.binaryType = 'arraybuffer'forArrayBuffer. A message is at most 16 MB. A failed connection fireserrorthenclose(code1006), and theerrorevent has a non-standardmessagesaying why. XMLHttpRequestis built onfetch, with the same rules. It's asynchronous only,responseTypecan be'','text','json','arraybuffer'or'blob', anduploadfires no events.- Remote images (the
srcofCanvasImageandImage) and videos need thenetworkpermission too. - When content is removed or stopped, its requests and connections are cancelled, with no more callbacks.
Without the network permission (the user denied it) the content runs as usual: show that it's offline rather than retrying again and again.
