electron: preload doesn't take path relative to app folder

I if want to preload a file for a webview tag and just pass in ./myFile.js to make it relative to the apps folder, i get the Only "file:" protocol is supported in "preload" attribute. error.

<webview src="http://page.com" preload="./myFile.js"></webview>

If i use the file:// protocol i can’t pass in a path which is relative to the electron app folder. I tried file://./myFile.js and file://myFile.js

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Comments: 17 (3 by maintainers)

Most upvoted comments

@frozeman how did you pass the __dirname into the render process?

Thanks!

So my webview has the preload=file://./assets/webviewInjectedScript.js. Without file://, electron cries me an error.

Opening the dev tools for the webview, and with a breakpoint at module.js#455 (where the MODULE_NOT_FOUND error is thrown), the search path seems to be :

/Users/marcelfalliere/my_app_electron_vue/node_modules/electron/dist/Electron.app/Contents/Resources/electron.asar/renderer/api/exports

After extracting electron.asar (with this tool), there’s no such file webviewInjectedScript.js so no wonder it finds it.

How can I tell electron to pack webviewInjectedScript.js in this asar file ?

This is a headache, friends.

As for how to pass the __dirname down: attach it to the app (electron.app.dirname = __dirname) and then use Electron’s remote to access it from the renderer app (electron.remote.app.dirname) and the use it in your templates or wherever you build the src attribute of the webview elements.

@fineline how did it ? how to change the configuration ?

@marcelfalliere I changed my dev configuration to reference the file directly in its location in my source project and that approach works for me.

I solved it now by providing an absolute path passing down the __dirname to the render process.

But you should update you example, as its misleading:

<webview src="https://www.github.com/" preload="./test.js"></webview>

https://github.com/atom/electron/blob/master/docs/api/web-view-tag.md#preload