Skip to content

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

@4lllex

Description

@4lllex
<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
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions