【问题标题】:Outputting base64 image data to new window without getting blocked?将base64图像数据输出到新窗口而不会被阻止?
【发布时间】:2013-04-25 05:26:54
【问题描述】:

现在有点 Javascript 的噩梦。

我正在使用 html2canvas 将 div 转换为画布,然后使用.toDataURL 将画布转换为 base64 数据流。

我想在新窗口中打开 base64 图像数据,但它被我测试过的每个弹出窗口阻止程序阻止。

这是我的函数示例

function generateImage(xarg){
    var divid= document.getElementById(xarg);
    html2canvas(divid, {
        onrendered: function(canvas) {
            var imgdata = canvas.toDataURL("image/png");
            window.open(imgdata);
        }
    });
}

知道为什么我的window.open 被屏蔽了吗?

编辑:我的另一个想法是开始下载图像,但我发现的每个解决方案都需要将数据更改为 image/octet-stream,这会弄乱文件类型,而且我的用户不会能够处理这个问题(尤其是那些在移动设备上的)。 我最初有一篇更长的帖子来解释我的情况,但为了简洁起见,我删掉了它。

【问题讨论】:

  • 这是否发生在click 事件中?或者你在其他时间运行这个?您是否尝试将 imgdata 替换为 "" 以查看它是否会打开一个空窗口?
  • @Ian 我有一个<a>,它调用onClick 属性中的函数。刚试过window.open("");,它仍然被阻止。我知道我在这里做错了什么被标记为恶意,我只是不确定是什么。
  • 我打赌onrendered 方法是一个异步方法,因此范围失去了“点击”上下文,因此被弹出窗口阻止程序阻止(就像其他由window.open 打开的弹出窗口一样,而不是由click 事件)
  • 这不是恶意的,只是因为该方法是异步的,当它被执行时,浏览器并不知道它最初是由click事件触发的(为了不会被屏蔽)
  • 是的,这是浏览器防止网站在没有用户交互的情况下无限/无法控制地生成弹出窗口的方式。所以既然你说这是从click事件调用的,我猜问题是因为onrendered是异步的

标签: javascript jquery base64


【解决方案1】:

由于异步打开方式(甚至来自点击事件的回调)而导致弹出窗口被阻止的其他直接响应。我通过以下方式解决了这个问题: - 直接在点击处理程序上打开一个空白弹出窗口 - 启动 html 内容的“canva-ification” - 创建一个临时表单,在弹出窗口中发布 Canva base64 数据

这种方法的缺点是用户在生成画布时弹出空白。我希望这会有所帮助。

function clickHandler(elementId /*the id of the element to convert to an image */) {
    // opens the popup directly -> not blocked by browsers
    var popup = window.open('about:blank', 'screenshotWindow', 'width=950,height=635');

    // creates the form
    var form = window.document.createElement('form');
    form.setAttribute('method', 'post');
    form.setAttribute('target', 'screenshotWindow');
    window.document.body.appendChild(form);

    html2canvas(window.document.getElementById(elementId), {
        onrendered: function(canvas) {
            // posts the base64 content in the popup with the form and removes it
            form.setAttribute('action', canvas.toDataURL('image/png'));
            popup.focus();
            form.submit();
            window.document.body.removeChild(form);
        }
    });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-05
    相关资源
    最近更新 更多