melon
melon
May 8, 2018 · 1 min read

如何利用javascript判斷網頁是否在in-app瀏覽器(WebView)開起

要知道網頁是否在in-app瀏覽器(WebView)開起要利用 navigator.userAgent

通常用WebView開啟的會包含WebView或wv等關鍵字

再用正規表達式比對一下就可以了

function isWebview() {
var useragent = navigator.userAgent;
var rules = ['WebView','(iPhone|iPod|iPad)(?!.*Safari\/)','Android.*(wv|\.0\.0\.0)'];
var regex = new RegExp(`(${rules.join('|')})`, 'ig');
return Boolean(useragent.match(regex));
}

Demo: https://jsfiddle.net/xxxooo24/wkpy5sup/3/

如果想要特別判斷是否用Facebook的in-app瀏覽器開起

可以用 FBAN 或 FBAV等關鍵字去判斷

下面列出幾個User Agent當作範例

可以看到Facebook in-app瀏覽器的User Agent會包含FBAN 或FBAV(粗體字部份)

Safari瀏覽器的User Agent則不會有那些關鍵字

Facebook for Android User-Agent

Mozilla/5.0 (Linux; Android 4.4.4; One Build/KTU84L.H4) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/33.0.0.0 Mobile Safari/537.36 [FB_IAB/FB4A;FBAV/28.0.0.20.16;]

Facebook for iOS User-Agent

Mozilla/5.0 (iPhone; CPU iPhone OS 8_2 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Mobile/12D508 [FBAN/FBIOS;FBAV/27.0.0.10.12;FBBV/8291884;FBDV/iPhone7,1;FBMD/iPhone;FBSN/iPhone OS;FBSV/8.2;FBSS/3; FBCR/vodafoneIE;FBID/phone;FBLC/en_US;FBOP/5]

Safari for iOS User-Agent

Mozilla/5.0 (iPhone; CPU iPhone OS 8_2 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12D508

判斷條件可參考下面

function isFacebookApp() {
var useragent = navigator.userAgent || navigator.vendor || window.opera;
return (useragent.indexOf("FBAN") > -1) || (useragent.indexOf("FBAV") > -1);
}

*想要查詢 in-app瀏覽器的 User Agent, 可以到下面的網址

https://developers.whatismybrowser.com/useragents/explore/software_type_specific/in-app-browser/

*user agent可以被輕易修改所以不是非常可靠, 不要用它做為判斷在一些重要的資訊


melon

Written by

melon

Front End Engineer in Sydney.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade