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

Script tags are reexecuted when navigating back from a page with an error status code using browser's back button #1249

Open
hoshiumiarata opened this issue Apr 21, 2024 · 0 comments

Comments

@hoshiumiarata
Copy link

I ran into this issue when implementing error pages in a Rails application.
When you navigate to a page with an error status code (e.g., 404) from a page with a status code of 200, and then navigate back using the browser's back button, the script tags are reexecuted. This leads to a situation where some JavaScript libraries (e.g., Stimulus) initialize multiple times and do not work correctly. There is no such behavior when navigating between pages with a status code of 200 or when not using Turbo, so it seems like a bug to me.

Minimal sample code to reproduce the issue (using Express.js, but can be reproduced with any server-side framework):

const express = require('express')
const app = express()
const port = 8888

app.get('/', (req, res) => {
  res.send(`
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Hello</title>
  <script type="module">
    import "https://unpkg.com/@hotwired/turbo@8.0.4/dist/turbo.es2017-esm.js";
  </script>
  <script type="module">
    import { Application, Controller } from "https://unpkg.com/@hotwired/stimulus@3.2.2/dist/stimulus.js";
    window.Stimulus = Application.start();
    Stimulus.debug = true;

    Stimulus.register("hello", class extends Controller {
      connect() {
        alert("hello connect");
      }
    })
  </script>
</head>
<body>
  <div data-controller="hello"></div>
  <a href="/404">to 404</a>
</body>
</html>
  `)
});

app.get('*', function (req, res) {
  res.status(404).send("404");
});

app.listen(port, () => {
  console.log(`Listening on port ${port}`)
})

Every time you navigate back to the page with the status code of 200, the alert message is displayed n + 1 times, where n is the number of times you navigated to the page with the status code of 404.

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