Small coding victory with React Native and WordPress

I just launched a very early preview of my React Native app for my blog that uses WordPress and its REST API as a backend. Naturally, I’d like to know how much traffic the app drives to the blog. I monitor the stats for the website with the popular Jetpack plugin. I’ve seen referrals to links from Android apps before so I just assumed that WebViews embedded in native Android apps used the application ID as the referrer.

I hadn’t seen any referrals from my own app so I was already open to the possibility that it might be something that I’d have to implement specifically. While I was the only person using the app, it wasn’t an urgent matter but now that I had deployed it to the PlayStore, it became essential, so I went at it.

My first idea was that maybe I had to set the user-agent.

<WebView
userAgent="android:com.kelvinpompey"
></WebView>

I then ran the app, opened a post, then went to the WordPress stats page to see the result. I saw that there was a view to the post but no reference to the user-agent that I had set.

I then began to think that I might have to set the referrer value specifically. I checked the React Native docs and saw that I could pass custom headers as an attribute of the source property for the WebView.

const headers = {'referer': "android:com.kelvinpompey"};

kelvinpompey.me app
Oversized Play Store Button

I ran another test and now the app was appearing in the referrer list! Great, but I had another problem. When I load the article in the app it would display the Play Store button that links to the app. I had added that to the website earlier. I had configured it such that it would only display on handset-sized displays and not on the desktop but I don’t want it displayed when the page is loaded from the app.

The thought process is probably obvious. I then began thinking that I needed some way to detect if the page is being loaded from the app and hide or not display the button in that case. It then occurred to me that I could probably test for the referrer in the HTTP header from the website.

I went to the website and added a test for it in the child theme that I was using.

<?php if($_SERVER['HTTP_REFERER'] != 'android:com.kelvinpompey'): ?></code>
<div class="play-button">[button code...]</div>
<?php endif; ?>

I ran the app again and now the button was gone! Sweet. I pushed an update to the PlayStore and thought that given how small a change it was, it would have been nice at the point if I didn’t have to go through the PlayStore. Maybe it was time to add Microsoft’s code push! Maybe, but that’s for another day! 🙂

Leave a Reply