Electron iframe: require is not defined

Viewed 1768

I want to embed a HTML file inside of my electron app. I chose to use iframe, however - when I do this - it seems like I can no longer use node.js. Any attempt at using require("electron") will show that require is not defined. Any ideas?

Thanks in advance!

  • Stijn
1 Answers

if you don't mind a late answer, you should probably use a <webview>, as it gives you a more fine grained control on what you need. If, however, you really need to use an <iframe>, you have two choices:

  1. use parent.require (parent accesses the iframe parent, which should be your window)
  2. on the load event, copy the parent window's require to the iframe one:
iframe.onload = function () {
  const iframeWin = iframe.contentWindow
  iframeWin.require = window.require
})

The only "downside" is that your included packages will be accessing the main window DOM instead of the iframe's one, which means that none of the iframe window global variables will exist and, more importantly, document will access the window DOM (querySelector and getElemementBy methods won't really work). Whether this is a problem for you depends on how you organise your code, so good luck there

Related