javascript エラー「Uncaught TypeError: window.location.href is not a function」の解決方法

javascript エラー「Uncaught TypeError: window.location.href is not a function」の解決方法

javascriptで、エラー「Uncaught TypeError: window.location.href is not a function」が発生した場合の原因と解決方法を記述してます。「location.href」の引数にURLを指定した場合に発生します。「chrome」や「firefox」や「safari」の各ブラウザのエラーメッセージの画像もキャプチャしてます。

環境

  • OS windows11 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 107.0.5304.107

エラー内容

以下の、「https://mebee.info/」に画面遷移しようとしたコードで発生。

window.location.href('https://mebee.info/');

エラーメッセージ

Uncaught TypeError: window.location.href is not a function

画像

firefox106の場合では、以下のエラーが発生します。

Uncaught TypeError: window.location.href is not a function

画像

safari15.5では、以下のエラーとなります。

TypeError: window.location.href is not a function. (In 'window.location.href('https://mebee.info/')', 'window.location.href' is "http://xxxx.com/sample.html")

画像

原因

「location.href」は「=」で文字列を指定する必要があるため

解決方法

「=」で文字列を指定します。

window.location.href = 'https://mebee.info/';

「()」で指定するのであれば「location.assign」を使用する

window.location.assign('https://mebee.info/');