LoginSignup
1
1

More than 5 years have passed since last update.

相対パスのリンクを絶対パスに書き換える(pushState対策)

Last updated at Posted at 2016-09-06

相対パスのリンクが存在するページで pushState 使って異なるパスへ履歴(URL)書き換えると、元々の相対パスリンクとカレントパスの関係がずれてリンク先が 404 になる問題が起きた。

対応コード

とりあえずページ読み込み時に $("a[href]") に対して (e)=>{e.href=e.href} をかける感じで対応してみた。その後 form[action] でも同じ問題が発生することに気づいたのでそちらも同じように対応した。

これをDOMContentLoadedのタイミングで実行する
//pushStateでカレントパスが変わると静的な相対パスが404になる問題の対処)
Array.prototype.slice.call(document.querySelectorAll('a[href]:not([href^="#"]):not([href=""])'))
  .forEach(function(e){e.href = e.href});
Array.prototype.slice.call(document.querySelectorAll('form[action]'))
  .forEach(function(e){e.action = e.action});

とりあえず今のところ特に問題も無くいい感じに対応できたっぽい。

説明

a.href って元の属性が相対パスで書いてあっても絶対URLが帰ってくるんだよね。だから a.href = a.href ってすると、一見意味なさげなコードに見えて相対パスが絶対パスになってくれる効果がある。
form.action も同じで相対パスが絶対パスになってくれるので上手くいく。

1
1
1

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