I know how to send message from JS to native IOS swift app:
func userContentController(userContentController: WKUserContentController!, didReceiveScriptMessage message: WKScriptMessage!) {
println("JavaScript is sending a message \(message.body)")
}
and JS:
webkit.messageHandlers.callbackHandler.postMessage("Hello from JavaScript");
My question: is it possible to directly call a function in the native app rather then receiving the message in my example code.
say i want in the JS to use something like:
webkit.messageHandlers.someFunctionName()
The reason i am asking is that In Android thats how it works
WKWebView supports only the raw message passing interface. You have to wrap it for complex interactions between JS and native.
I created a project named XWebView which offers language binding styled API based on the raw message passing of WKWebView. It's written in Swift.
For example, you can write a plugin in Swift:
class Plugin : NSObject {
func someFunctionName() {
doSomeThing()
}
}
Expose an instance of the plugin to JavaScript before loading HTML:
let webView = WKWebView(frame: frame, configuration: WKWebViewConfiguration())
webView.loadPlugin(Plugin(), namespace: "foo")
Call the function from JavaScript:
window.foo.someFunctionName()
It's really easy and straightforward. For more details, please check the project's page.
You could try to use the url parameters
, like you would connect to PHP using swift
Here is an example of how to get the url parameters in javascript: Get url parameter jquery Or How to Get Query String Values In js
Then when you run the javascript you can check, in the check what the url parameters
are and then run a function based on that
like this
the url is example.com
we use the parameter command
, to say what function to run
example.com?command=foo
then we should have someting like this in the javascript
if(command='foo'){
//run function
runFoo();
}
Then you could also use the url parameters to set parameters into the function
If you choose PHP
if you choose to use php, this is the same thing you can do with $_GET['command'];