基于星期几和时间重定向的Javascript

时间:2019-08-25 12:22:45

标签: javascript

我正在尝试根据星期几进行重定向,如果可能的话,也希望根据时间范围进行重定向。例如从安息日的星期五下午2点到星期六晚上10点。

谢谢,谢谢。

mw4

1 个答案:

答案 0 :(得分:0)

设置规则列表,例如:

const rules = [
    { day: 0, from: 0, to: 20, url: 'https://google.com/' }, // Redirect for Sunday 00:00 - 20:00
    { day: 0, url: 'https://ya.ru/' }, // Redirect for Sunday for any other time
    { day: 5, url: 'https://bing.com/' }, // Redirect for Friday
    { from: 12, to: 13, url: 'https://rambler.ru/' }, // Redirect for all days 12:00 - 13:00
    { url: 'https://duckduckgo.com/' }, // Redirect for all other cases
];

然后找到当前满足条件的第一条规则:

function getRedirectUrl() {
    const now = new Date();
    const today = now.getDay();
    const hours = now.getHours();

    const first = rules.find(item =>
        (item.day === undefined || item.day === today) &&
        ((item.from === undefined || item.from >= hours) && (item.to === undefined || item.to < hours))
    );

    return first.url;
}

然后进行重定向:

window.location.href = getRedirectUrl();

现在所有代码

<script>
    const rules = [
        { day: 0, from: 0, to: 20, url: 'https://google.com/' }, // Redirect for Sunday 00:00 - 20:00
        { day: 0, url: 'https://ya.ru/' }, // Redirect for Sunday for any other time
        { day: 5, url: 'https://bing.com/' }, // Redirect for Friday
        { from: 12, to: 13, url: 'https://rambler.ru/' }, // Redirect for all days 12:00 - 13:00
        { url: 'https://duckduckgo.com/' }, // Redirect for all other cases
    ];

    function getRedirectUrl() {
        const now = new Date();
        const today = now.getDay();
        const hours = now.getHours();

        const first = rules.find(item =>
            (item.day === undefined || item.day === today) &&
            ((item.from === undefined || item.from >= hours) && (item.to === undefined || item.to < hours))
        );

        return first.url;
    }

    function redirect() {
        window.location.href = getRedirectUrl();
    }
</script>

现在,您可以在需要时致电redirect()