如何在特定时间重定向页面

时间:2019-01-31 00:10:35

标签: javascript html

我正在尝试找到一种方法,以便每天在美国东部标准时间上午7:58将页面重定向到另一页面,然后每天在美国东部标准时间晚上9点重定向回该页面,对此有什么想法或建议?

2 个答案:

答案 0 :(得分:0)

我为您创建了一些东西,每隔x秒触发一次函数,然后将其重定向到您想要的任何地方

window.setInterval(function(){ //This will trigger every X miliseconds

    var date = new Date(); //Creates a date that is set to the actual date and time

    var hours = date.getHours(); //Get that date hours (from 0 to 23)
    var minutes = date.getMinutes(); //Get that date minutes (from 0 to 59) 

   if (hours == 7 && minutes == 58 ){
       //redirect to where you want
   } else if( hour = 21 && minutes == 00){
       //redirect to where you want
   } 

}, 1000); //In that case 1000 miliseconds equals to 1 second

现在,讨论UTC并进行设置。您可以在创建日期时进行设置,其中只有一个主题与此相关:Create a Date with a set timezone without using a string representationHow to initialize a JavaScript Date to a particular time zone

有时候我会推荐使用诸如moment.js之类的东西。 希望我的回答对您有所帮助

答案 1 :(得分:0)

重定向到另一个页面很简单,但是重定向回到原始页面并不容易。

为达到此效果,您可以考虑将要导航的页面包装在<iframe>元素中,其中包含<iframe>的页面在那些关键时刻控制导航。 / p>

您还可以考虑设置一个间隔,以每隔一分钟使用setInterval()检查并运行此导航逻辑(如果需要)。为了简化时间的操作和查询(相对于您的时区),您可能会发现momentjs很有帮助。

这些想法在以下代码段中进行了组合:

/*
Run this logic once per minute
*/
const oncePerMinute = () => {

  /*
  Get iframe and current iframe src
  */
  const iframe = document.querySelector('iframe');
  const iframeSrc = iframe.getAttribute('src');
  
  /*
  The url's to display for either time slot
  */
  const dayUrl = 'daytimeurl'
  const nightUrl = 'nighttimeurl'

  /*
  Adjust time to EST (-5hr)
  */
  const momentEST = moment().utc().utcOffset('-0500');

  /*
  If between 7:58am and 9:00pm update iframe to show day url
  */
  if(momentEST.isBetween(moment('7:58am', 'h:mma'), moment('9:00pm', 'h:mma'))) {
    
    if(iframeSrc !== dayUrl) {
      iframe.setAttribute('src', dayUrl);
    }
  }
  /*
  Othwise, update iframe to show night url
  */
  else {
    
    if(iframeSrc !== nightUrl) {
      iframe.setAttribute('src', nightUrl);
    }
  }
}

/*
Will set interval to run oncePerMinute every minute
*/
setInterval(oncePerMinute, 1000 * 60);

oncePerMinute();
iframe {
  position:fixed;
  top:0;
  left:0;
  width:100%;
  height:100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
<iframe></iframe>

相关问题