It is possible to send JavaScript code to be executed on client from a C++ module loaded on server.
Run JS code on client
The JS code you want to execute on client can be sent from server to client as a string using WApplication’s doJavaScript function (SDK/Headers/wt_inc/Wt/WApplication). Your module needs to link against Wt lib located in SDK (SDK/Libraries/wt_lib/).
Include XeUpdateLock.h from SDK (SDK/Headers/inc/) - it will also include Wt/WApplication
Take XeUpdateLock before getting WApplication object
Get WApplication object and call doJavaScript on WApplication object
Example how to print something to console:
XeUpdateLock lock; if (lock) { Wt::WApplication::instance()->doJavaScript("console.log('This message is printed to console');"); }
Note: If you do not take XeUpdateLock, Wt::WApplication::instance()
will return a null pointer.
The JS code is evaluated on client by calling window.eval() function before run and an exception will be thrown if it is not valid what will cause a client disconnect.
Post a message to parent frame
You can use this mechanism and run JavaScript code that will post a message from iframe to its parent. There are two ways to send a message:
Via ‘xepstm_to_p’ event
Create a xepstm_to_p event with two members _m for message name and _mc for message content.
XeUpdateLock lock; if (lock) { std::string js = "{" "var event = document.createEvent('Event');" "event.initEvent('xepstm_to_p', true, true);" "event._m = messageName;" "event._mc = messageContent;" "window.dispatchEvent(event);" "}"; Wt::WApplication::instance()->doJavaScript(js); }
messageName and messageContent are arbitrary strings.
This will send a JSON message like this to parent frame:
{ messageName: messageName, message: messageContent }
Using postMessage
Alternatively you can send any message formatted as you want to the parent frame using window parent’s postMessage function. E.g. just send a string:
XeUpdateLock lock; if (lock) { std::string js = "if (window.parent) {" "window.parent.postMessage("my message", '*');" "}"; Wt::WApplication::instance()->doJavaScript(js); }