LoginSignup
1
1

More than 3 years have passed since last update.

JSでブラウザ毎にメソッドが対応しているかを判定して条件分岐をする

Posted at

暗号化に使えるCrypto.subtleを例にとってみる。最近のブラウザであれば crypto.subtle が使えるが、httpだと動かないし、IEは部分対応となっている。

crypto.subtleが使える場合と使えない場合で処理を分ける場合にどのようにやるのか調べてみた。

typeofで判定をする

http,httpsのページで実行をしてみればわかるが、typeofで判定をすればそのブラウザで使用できるのかどうかがわかるため、条件分岐ができる。

if (typeof crypto.subtle === 'object') {
// ブラウザでcrypto.subtleが使えるので、そのまま
  crypto.subtle.importKey();
} else {
  // 何かしら他の処理をする
}

chromeのhttpsのサイトで実行してみた結果

typeof crypto.subtle
"object"

chromeのhttpのサイトで実行してみた結果

typeof crypto.subtle
"undefined"
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1