LoginSignup
3
8

More than 1 year has passed since last update.

【React】別タブが閉じたことを検知する【JavaScript】

Last updated at Posted at 2021-07-08

はじめに

「外部サービスを別タブで開き、その別タブが閉じたことを元のタブで検知したい」
なんて時に使える方法をご紹介します。

タイトルにReactを入れておりますが、Vueとかでも使えます。

結論

sample.js
const url = "https://hogehoge.com" //任意の別タブのURL
const win = window.open(url, "_blank")
if(win) {
 const timer = setInterval(() => {
  if(win.closed) {
    window.clearInterval(timer);
    // 別タブ閉じた時にしたいこと
  }
}, 500);

簡単に解説

const win = window.open(url, "_blank")

定義したurlを別タブで開きます

setInterval(() => {...}, 500)

500ミリ秒ごとに、{...}を実行します
WindowOrWorkerGlobalScope.setInterval()

window.clearInterval(timer)

windowがclosedの場合、setIntervalを使用して設定された繰り返し動作をキャンセルします。
window.clearInterval

追記

@9447al 様より、clearIntervalを使用しない方法をコメント頂けました。
そちらもご参照ください!

最後に

結構最近はグローバルオブジェクトを使う機会が多い。
JS、、奥が深いぜ、、、

3
8
2

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
3
8