简体   繁体   中英

Can I create an HTML page using javascript in Electron?

I know there is a way to load an html page

win.loadURL("index.html");

But, can I just load an html page when it's not from a file, just dynamically generated by javascript?

For example:

str = generateHtmlPage();
win.loadstr(str);  // just load from a string

Javascript uses the DOM (Document Object Model) to interact with an HTML file. And is executed as part of parsing the page. Logically, you can construct an entire page using append to the html page.

document.write("Build my page here.");

But this solution seems cumbersome and not an advisable solution. Perhaps, edit your question to identify your objective and I might be able to help you find the appropriate solution.

[timo] have answered my question with the gist from [dannvix]:

https://gist.github.com/dannvix/dc0efdbb75bf79a79d1c#file-electron-main-js-L21-L27

here is the code:

// main.js for Electron
var app = require("app"),
    BrowserWindow = require("browser-window");

app.on("window-all-closed", function() {
  app.quit();
})

var mainWindow = null;
app.on("ready", function() {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    center: true,
    resizable: true,
    frame: true,
    transparent: false,
  });
  mainWindow.setMenu(null);

  // create BrowserWindow with dynamic HTML content
  var html = [
    "<body>",
      "<h1>It works</h1>",
    "</body>",
  ].join("");
  mainWindow.loadURL("data:text/html;charset=utf-8," + encodeURI(html));

  mainWindow.openDevTools();
  mainWindow.on("closed", function() {
    mainWindow = null;
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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