Skip to content

Exposing TypeScript functions to the browser

Justin Bush edited this page Jun 5, 2024 · 9 revisions

The goal of this article is to explore the possible options for exposing functions, variables and WebKit message handlers to the browser in the simplest and quickest way possible.

In order to explore these options fully, let's take a look at what a vanilla implementation might look like:

Vanilla Exposure

Define types to be exposed:

declare global {
  interface Window {
    webkit: {
      messageHandlers: {
        // Example 1
        someMessageHandler: {
          someStringFunction: (someParam: string) => void;
        };
        anotherMessageHandler: {
          someBooleanFunction: (someParam: boolean) => void;
        };
      };
    };
    // Example 2
    sendMessageToReactWebApp: (message: string) => void; 
    showReactSidebar: () => void;
  }
}

Then, define the function body for each:

Example 1

const sendCallToSwiftApp = () => {
  if (
    window.webkit &&
    window.webkit.messageHandlers &&
    window.webkit.messageHandlers.someStringFunction
  ) {
    window.webkit.messageHandlers.someMessageHandler.someStringFunction(
      'WebKit message handler received!'
    );
  } else {
    console.warn("Message handler 'someMessageHandler' is not available.");
  }
}
sendCallToSwiftApp()

Example 2

const sendMessageToReactWebApp = useCallback(
(message: string) => {
  // do something with message
  console.log('Message received from React app:', message);
});

useEffect(() => {
  window.sendMessageToReactWebApp = sendMessageToReactWebApp;
}, [sendMessageToReactWebApp]);

That's a lot of code. It sure would be nice if we could simplify a lot of this.

Clone this wiki locally