简体   繁体   中英

Redirect automatically only from a particular page - Rails

I just asked a question and received some good help on redirecting to a particular page if no user action after 15 seconds. So, I have javascript that will redirects the page but I only want it to happen from a particular page, as it is right now it happens from every page in the website. To be clear, Only from the user show page to I want it then to redirect after 15 seconds to the root page. I'll show the current Javascript for clarity.

redirect.js:

 var redirectTimeoutId = window.setTimeout(redirectToHomepage, 15000)

function redirectToHomepage() {
  window.location.href = '/subscribers/search'; // or whatever your homepage would be
}

window.addEventListener('click keypress mousemove', function() {
  window.clearTimeout(redirectTimeoutId)
}, true)

As you can see no where does it specify that it should only redirect from a particular page. Does anybody know how to with that?

You could only add this JS on the page you want it to trigger on but that is against Rails conventions. Your other options is to check what page you are on. There are many ways to do this but something like this if statement should work.

if(window.location.pathname == "/path/to/user/show/page") {
  var redirectTimeoutId = window.setTimeout(redirectToHomepage, 15000)

  function redirectToHomepage() {
    window.location.href = '/subscribers/search'; // or whatever your homepage would be
  }

  window.addEventListener('click keypress mousemove', function() {
    window.clearTimeout(redirectTimeoutId)
  }, true)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM