简体   繁体   English

setTimeout无法在Chrome中运行

[英]setTimeout not working in Chrome

This question is for a colleague. 这个问题是针对同事的。 He is having an issue in Chrome with the following code snippet: 他在Chrome中遇到了一个问题,其中包含以下代码段:

function showEmailClient(emailContent, url, providerContactId) {
    window.location = emailContent;
    if (providerContactId != undefined) {
        setTimeout(function() {
            clientSideRedirect(url + providerContactId);
        }, 5000);
    }
    else {
        setTimeout(function() {
            clientSideRedirect(url);
        }, 5000);
    }
}​

The setTimeout functions are getting called immediately in Chrome instead of waiting the five seconds they are supposed to. setTimeout函数会立即在Chrome中调用,而不是等待它们应该的五秒钟。 Any ideas? 有任何想法吗?

Update 更新

emailContent is a mailto string, eg 'mailto:support@somewhere.com' which causes the user's default mail client to open, not the page to redirect. emailContent是一个mailto字符串,例如'mailto:support@somewhere.com',它会导致用户的默认邮件客户端打开,而不是要重定向的页面。

window.location = emailContent;

一旦命中此行,这将重定向浏览器。

From my experience, don't use use a window.location for bringing up the email client and doing a redirect on the same page - it's a beast. 根据我的经验,不要使用window.location来启动电子邮件客户端并在同一页面上进行重定向 - 这是一个野兽。 Instead, use a form for submitting the email using the System.Net.Mail namespace and objects in it, then do your redirect. 相反,使用表单使用System.Net.Mail命名空间及其中的对象提交电子邮件,然后执行重定向。 If that isn't an option, store the mailto data in session, redirect and then call the mail client when the page loads. 如果这不是一个选项,请将mailto数据存储在会话中,重定向,然后在页面加载时调用邮件客户端。 The only caveat about this approach is that the window.location will kill any responses that haven't been written, so you'll need to give the page some time to load using a timer event usually about 2000 milliseconds (if your page has dynamic data and has various load times, good luck!). 关于这种方法的唯一警告是window.location将终止任何尚未写入的响应,因此您需要给页面一些时间来加载使用通常大约2000毫秒的计时器事件(如果您的页面具有动态数据和各种加载时间,祝你好运!)。

This code snippet uses jQuery to wait for the document to be ready for use and adds 2000 milliseconds to ensure any responses are written. 此代码段使用jQuery等待文档准备好使用,并添加2000毫秒以确保写入任何响应。

function showEmailClient(mailto)
{
    $(document).ready(function ()
    {
        setTimeout(function ()
        {
            window.location = mailto;
        }, 2000);               
    });
}

protected void Page_Load(object sender, EventArgs e)
{
    if (Session["SendMail"] != null)
    {
        var mailto = Session["SendMail"].ToString();
        ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "ShowEmailClient", "showEmailClient('" + mailto + "');", true);
        Session["SendMail"] = null;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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