【问题标题】:electron: loading image into new window电子:将图像加载到新窗口
【发布时间】:2021-04-20 14:04:03
【问题描述】:

在电子应用程序中,我试图在窗口中显示本地磁盘中的图像 单击主窗口中的按钮时打开。 图像的路径仅在运行时已知。 我的第一种方法是生成一个加载模板 html 文件的新窗口 当该按钮上的点击事件被触发然后设置 此 html 模板中 img 元素的 src 属性, 但我没有成功处理定义的这个 img 元素 “imgView.html”(以下来自渲染器进程):

newWindowBtn.addEventListener('click', function(event){
    let win = new BrowserWindow({
    webPreferences: {
         nodeIntegration: true
         },
         width: 500, height:500});
    win.loadFile("imgView.html");
    // how can the img-element defined in the template imgView.html
    // be accessed here to set the src-attribute?
    win.show();
    win.on('close', function(){win=null})
})

我希望能够同时打开多个窗口,加载不同的图像。 我的第二种方法是动态生成要加载的 html:

var html = [
"<body>",
"<p>Sample image: </p>",
"<img src=\"img.png\" style=\"width:90%\">",
"</body>"
].join("")

并替换 newWindowBtn.addEventListener 事件函数中的 win.loadFile 命令 从上面与

    win.loadURL("data:text/html;charset=utf-8," + encodeURIComponent(html),
    {baseURLForDataURL: __dirname + "/imgDir/"}
    )

但显然找不到图像(页面的其余部分加载正常)。 我使用了baseURLForDataURL 的格式,但没有任何效果。 有什么想法吗?

【问题讨论】:

    标签: javascript html electron


    【解决方案1】:

    在某些情况下,我认为data:text/html;charset=utf-8," + encodeURIComponent(html) 是不够的,您需要使用base64 对html 进行编码:data:text/html;base64, + btoa(html)

    注意
    如果这不是解决方案,这意味着 Electron 不允许您调用图像,因为您要加载的页面被视为外部页面,您也必须使用 base64 对图像进行编码。

    【讨论】:

    • 非常感谢您的回复。我还没有找到模块 btoa - 它是 Node.js 的一些第三方扩展吗?我想知道手头的问题是否不能仅使用标准节点/电子模块以某种方式解决(通过将文件路径等数据动态传递到新窗口或通过如上所述动态生成 html)...
    • btoa 不是一个模块,它是一个用 javascript 实现的简单功能,它是一个原生浏览器功能:您不需要创建或添加模块或功能...
    猜你喜欢
    • 1970-01-01
    • 2015-06-10
    • 2013-05-04
    • 2010-11-22
    • 2020-06-15
    • 2020-07-24
    • 1970-01-01
    • 1970-01-01
    • 2012-05-17
    相关资源
    最近更新 更多