PageMessage ( )

Parameters

None.

Description

Returns the next message from the web page that runs the program, as a JSON handle, or 0.

When your program runs in a web page, the page can send it messages: a game exported for the web can hear from the page around it - a new level to load, the player's name, a pause button outside the game - and the online IDE's World Editor hears Blip's requests this way. Each message is a JSON value, usually an object. PageMessage returns a new JSON handle for the oldest message waiting, or 0 when none is waiting, so a loop that calls it until it returns 0 takes them all.

Messages arrive only while your program lets the page run: at Flip, WaitEvent, Delay and the other commands that wait. So a message never arrives halfway through your own code, and a program that never waits never gets one. Checking once a frame, just before or after Flip, is the usual pattern.

The handle is yours: read the message with JsonObjectGet and its friends, then release it with FreeJson. Answer with SendPageMessage. A page that wants an answer usually puts an id in its message; copy it into your answer, so the page knows which question you answered.

The page sends a message by posting {type: 'b3d-page-message', message: ...} to the window of the frame the program runs in. The online IDE does this through its own run frame.

On Windows and macOS there is no page, so PageMessage always returns 0. The command is there so that one program compiles and runs everywhere.


See also: SendPageMessage, JsonObjectGet, JsonStringify, FreeJson.

Example

; PageMessage Example
; -------------------

Graphics 640,480,0,2
SetBuffer BackBuffer()

received=0
latest$="(none yet)"

While Not KeyDown(1)

    ; Take every message the page has sent since the last frame
    message=PageMessage()
    While message<>0
        received=received+1
        ; Each message is a JSON value: keep it as text to show it
        latest=JsonStringify(message,0)
        FreeJson message
        message=PageMessage()
    Wend

    Cls
    Text 0,0,"Waiting for messages from the web page   Esc: exit"
    Text 0,20,"Messages received: "+received
    Text 0,40,"Latest message: "+latest
    If received=0 Then
        Text 0,80,"A page that runs this program in a frame can send it messages."
        Text 0,100,"On Windows and macOS there is no page, so PageMessage returns 0."
    EndIf

    Flip

Wend

End

Index