addScriptMessageHandler(_:contentWorld:name:)
Installs a message handler that returns a reply to your JavaScript code.
Declaration
func addScriptMessageHandler(_ scriptMessageHandlerWithReply: any WKScriptMessageHandlerWithReply, contentWorld: WKContentWorld, name: String)Parameters
- scriptMessageHandlerWithReply:
The message handler object that implements your custom code. This object must adopt the Wkscriptmessagehandlerwithreply protocol.
- contentWorld:
The content world in which to install the message handler. Use the content world to scope your message handler to specific parts of your JavaScript code.
- name:
The name of the message handler. This parameter must be unique within the user content controller and must not be an empty string.
The user content controller uses this parameter to define a JavaScript function for your message handler in all frames in the specified content world. The name of this function is
window.webkit.messageHandlers..postMessage(<messageBody>), where corresponds to the value of this parameter. For example, if you specify the stringMyFunction, the user content controller defines thewindow.webkit.messageHandlers.MyFunction.postMessage()function in JavaScript.
Discussion
To execute your handler’s code, call the JavaScript function that this method defines. You may pass a parameter value to the method. The user content controller packages that value into an appropriate type and delivers it to your content handler’s delegate method.