Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
806 views
in Technique[技术] by (71.8m points)

Detect in-app browser (WebView) with PHP / Javascript

I developed an app for iOS and Android which accesses an HTML file from my webserver using the in-app browser (Webview).

I don't want that a user can access this file without using the app. Is there a possibility to detect, if the user is accessing the file with the app or directly via a browser on this smartphone / tablet / computer? I think that a solution with PHP is much better, because Javascript can be switched off. At least Google Analytics can differentiate between Safari and Safari (in-app). It should work with every version of iOS and Android.

Thanks for your help.


Solution

After many attempts I finally found a working solution for me!

iOS: You can detect the difference between Safari and the in-app browser using the user agent. Probably there's a nicer solution, but it works.

// Safari (in-app)
if ((strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile/') !== false) && (strpos($_SERVER['HTTP_USER_AGENT'], 'Safari/') == false) {
    echo 'Safari (in-app)';
}

Android: The package name from the app is stored in the PHP variable $_SERVER['HTTP_X_REQUESTED_WITH'].

// Android (in-app)
if($_SERVER['HTTP_X_REQUESTED_WITH'] == "com.company.app") {
    echo 'Android (in-app)';
}

As Tim van Elsloo already noted HTTP headers can be faked and this is not absolutely secure.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'm not sure about Android, but when you're using the iOS SDK's UIWebView, it sends the name and version of your app as part of the user agent (YourApp/1.0).

You can then use PHP to check if your in-app webview is being used or not:

if (strpos($_SERVER['HTTP_USER_AGENT'], 'YourApp/') !== false)

I think Android does something similar as well.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...