Zhenyi Tan And a Dinosaur

Adding “Open in Mastodon” to your Mastodon App

I’m not launching a new app. This is just a simple guide for developers of Mastodon apps.

On iOS, the “open in X” behavior is typically implemented with Universal Links. However, since Mastodon is decentralized, there is no official list of URLs developers can use. Fortunately, we can create a simple Safari extension to work around this issue.

“I call on the power of the Mastodon!”

Creating the Safari Extension

  1. Register a custom URL scheme for your app from the Info tab of your project settings.

  2. Create a new Safari extension by choosing File → New → Target…, then choose Safari Extension.

  3. In the manifest.json file, update the "content_scripts" property to match every web page.

    "matches": [ "http://*/*", "https://*/*" ]

    You can also remove the "service_worker" and the "default_popup" properties if you don’t plan to use them.

  4. In the content.js file, paste in the following code:

    // A more reliable way is to check for an API response,
    // e.g. https://domain.name/api/v1/timelines/public?limit=1
    // but that requires an extra round trip to the server.
    // So we just do something quick and dirty:
    if (document.querySelector('[id*=mastodon]')) {
        // If you want to open your app only from the profile and post pages,
        // you can add an additional if statement.
        // if (location.pathname.match(/@(.+?)(\/|$)(\d+)?/))
        // The regex in this statement also lets you access the username and post ID,
        // in case you want to use a custom URL format.
        location.href = `blackranger:${location.host}${location.pathname}${location.search}`;

  5. That’s it!

Note: You will also need to handle the incoming URLs in your app by implementing the application(_:open:options:) method in your AppDelegate. If your app uses SwiftUI, you can use the onOpenURL(perform:) view modifier to handle the URLs.

Customizing the Extension

  1. You should update the extension’s name and description in the messages.json file.

  2. You should also add some icons for the extension. Use your app’s icon as the basis for the extension’s icons, but remember to add the rounded corners yourself. The toolbar icons should be monochrome PNG files with an alpha channel.

  3. To ensure that the extension is effective, you should instruct your users to enable the extension and grant it permission to access all websites.

  4. As an advanced option, you can add the domains of Mastodon URLs to a database when opening the app from those URLs. This will allow you to navigate directly to the appropriate view in your app when the user taps on a link without going through the app-Safari-app hoop.

The source code for this project is available on GitHub, and I’m happy to answer any questions you may have. You can reach out to me on Mastodon or via email.