Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prefetch doesn't handle links with data-turbo-frame="_self" #1349

Open
4lllex opened this issue Dec 9, 2024 · 0 comments
Open

Prefetch doesn't handle links with data-turbo-frame="_self" #1349

4lllex opened this issue Dec 9, 2024 · 0 comments

Comments

@4lllex
Copy link

4lllex commented Dec 9, 2024

<turbo-frame id="frame" target="_top">
  <a data-turbo-frame="_self" href="/test">_self in frame</a>     <!-- works -->
</turbo-frame>

<a data-turbo-frame="_self" href="/test">_self out of frame</a>   <!-- doesn't work -->

In both cases prefetch sends a turbo frame request with a header Turbo-Frame: _self. In a rails environment this will render turbo_rails/frame layout. When the link is in a frame, everything works. When the link is outside of the frame, the page does a full reload due to mismatching data-turbo-track elements in the head tag.

Code shows _self to be left out:

prepareRequest(request) {
const link = request.target
request.headers["X-Sec-Purpose"] = "prefetch"
const turboFrame = link.closest("turbo-frame")
const turboFrameTarget = link.getAttribute("data-turbo-frame") || turboFrame?.getAttribute("target") || turboFrame?.id
if (turboFrameTarget && turboFrameTarget !== "_top") {
request.headers["Turbo-Frame"] = turboFrameTarget
}
}


Patch for a possible solution:

Turbo.session.linkPrefetchObserver.__proto__.prepareRequest = function(request) {
  const link = request.target

  request.headers["X-Sec-Purpose"] = "prefetch"

  const turboFrame = link.closest("turbo-frame")
  const turboFrameTarget = link.getAttribute("data-turbo-frame") || turboFrame?.getAttribute("target") || turboFrame?.id

  if (turboFrameTarget && turboFrameTarget !== "_top") {
    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    if (turboFrameTarget === "_self") {
      if (turboFrame) {
        request.headers["Turbo-Frame"] = turboFrame.id
      }
      return
    }
    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    request.headers["Turbo-Frame"] = turboFrameTarget
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

1 participant