Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

webkit.messageHandlers for React to inject JavaScript to Swift

I'm working with WKWebView, where I'm loading a webpage (React) to display. But my didFinish is getting triggered too early. So when my delegate notify about didFinish, then I do only see a white screen for a couple of seconds, before the actual data is loaded.

This is not working, causes white screen - before showing actual content

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {  
    activityIndicator?.stopAnimating()
}

Instead I read this article, telling me it should be possible to achieve, by letting the webpage, notify the Swift code when loaded.

https://medium.com/capital-one-developers/javascript-manipulation-on-ios-using-webkit-2b1115e7e405

I did implement the following code, in my Xcode project

override func viewDidLoad() {
    super.viewDidLoad()

    let userContentController = WKUserContentController()
    userContentController.add(self, name: "test")
}

extension DashboardViewController: WKScriptMessageHandler {
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        if message.name == "test", let messageBody = message.body as? String {
            print(messageBody)
        }
    }
}

But, now we are here. I don't know where to put this, since my web app is written in React.

<script>   
    function printHelloWorld() {
        window.webkit.messageHandlers.test.postMessage("Did finish loading");   
    }   

    window.onload = printHelloWorld; 
</script>

My React component

class Page extends React.Component<{ location, match }> {

    public render() {
        const content = (
            <div className="row">
              <p>Content</p>
            </div>
        );

        return (
            content
        )
    }
}

export default Page;

Can anyone tell me, how I can use window.webkit.messageHandlers.test.postMessage within my React component?

like image 821
Grumme Avatar asked Nov 24 '25 11:11

Grumme


1 Answers

Try calling the function when the component mounts:

class Page extends React.Component<{ location, match }> {

    componentDidMount() {
        window.webkit.messageHandlers.test.postMessage("Did finish loading");
    }
    render() {
      ...
    }
}

It's sort of the onload for a React component.

More info about componentdidmount

like image 109
bamse Avatar answered Nov 27 '25 00:11

bamse



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!