Giter VIP home page Giter VIP logo

electron-serve's Introduction

electron-serve

Static file serving for Electron apps

Normally you would just use win.loadURL('file://…'), but that doesn't work when you're making a single-page web app, which most Electron apps are today, as history.pushState()'ed URLs don't exist on disk. It serves files if they exist, and falls back to index.html if not, which means you can use router modules like react-router, vue-router, etc.

Install

npm install electron-serve

Requires Electron 8 or later.

Usage

const {app, BrowserWindow} = require('electron');
const serve = require('electron-serve');

const loadURL = serve({directory: 'renderer'});

let mainWindow;

(async () => {
	await app.whenReady();

	mainWindow = new BrowserWindow();

	await loadURL(mainWindow);

	// Or optionally with search parameters.
	await loadURL(mainWindow, {id: 4, foo: 'bar'});

	// The above is equivalent to this:
	await mainWindow.loadURL('app://-');
	// The `-` is just the required hostname
})();

API

loadUrl = serve(options)

options

Type: object

directory

Required
Type: string

The directory to serve, relative to the app root directory.

scheme

Type: string
Default: 'app'

Custom scheme. For example, foo results in your directory being available at foo://-.

hostname

Type: string
Default: '-'

Custom hostname.

file

Type: string
Default: 'index'

Custom HTML filename. This gets appended with '.html'.

isCorsEnabled

Type: boolean
Default: true

Whether CORS should be enabled. Useful for testing purposes.

partition

Type: string
Default: electron.session.defaultSession

The partition where the protocol should be installed, if not using Electron's default partition.

loadUrl(window, searchParameters?)

The serve function returns a loadUrl function, which you use to serve your HTML file in that window.

window

Required
Type: BrowserWindow

The window to load the file in.

searchParameters

Type: object | URLSearchParams

Key value pairs or an URLSearchParams instance to set as the search parameters.

Related

electron-serve's People

Contributors

akshitkrnagpal avatar apetho avatar dedo1911 avatar ffflorian avatar hadeeb avatar ibash avatar juliangruber avatar laztoum avatar mhkeller avatar richienb avatar sindresorhus avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

electron-serve's Issues

Source maps cannot be loaded by Chrome DevTools

Issuehunt badges

When I am serving a specific directory the devtools always complain that the source maps couldn't be loaded. That also makes sense cause Chrome will try to fetch those relative to directory that is served, meaning it looks for source maps in app://-/Users/... and obviously it cannot find them there, cause that path is not a correct path to the node modules where the source maps are located. Any idea what I could do to fix this?


IssueHunt Summary

Backers (Total: $40.00)

Become a backer now!

Or submit a pull request to get the deposits!

Tips


IssueHunt has been backed by the following sponsors. Become a sponsor

Error: ERR_FILE_NOT_FOUND (-6) loading 'app://-/'

I have an electron-forge setup that I want to add electron-serve to.

I tried creating a /renderer directory and putting an index.html in it and using this code

const loadURL = serve({ directory: "renderer" });

const createWindow = () => {
    const mainWindow = new BrowserWindow({
        width: 1600,
        height: 800,
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false,
        },
    });

    // and load the index.html of the app.
    // original electron-forge command
    // mainWindow.loadURL(MAIN_WINDOW_WEBPACK_ENTRY)
    loadURL(mainWindow);

    // Open the DevTools.
    // mainWindow.websContents.openDevTools();
};

But I end up with

UnhandledPromiseRejectionWarning: Error: ERR_FILE_NOT_FOUND (-6) loading 'app://-/'
    at rejectAndCleanup (electron/js2c/browser_init.js:217:1457)
    at Object.failListener (electron/js2c/browser_init.js:217:1670)
    at Object.emit (events.js:315:20)

Am I missing something simple?

Benefits of using electron-serve in Angular

Hi,

I am currently developing an Electron application that renders an Angular application using standard win.loadURL('file://…'). It uses the router module from Angular internally for routing tasks and it works ok. What is the advantage of using this library over the standard approach?

Thanks

Relative path resolution for require does not work

Issuehunt badges

When I use electron-serve in electron-quick-start require('./renderer.js') can't be resolved.

I have to use path.resolve within the require call to make that work:

<script>
  const path = require('path');
  require(path.resolve('./renderer.js'));
</script>

Any way that can be fixed so that relative requires work with electron-serve?

There is a $40.00 open bounty on this issue. Add more on Issuehunt.

Unclear sentence in readme

The partition the protocol should be installed to, if you're not using Electron's default partition.

It looks like there's a duplicate subject here and the wrong "to". Should this read: "The partition should be installed too"?

Poor documentation.

You should consider that someone just want a detailed explaination on how this library works. I just learned Electron and I don't know how to implement this. Can you at least give more detail to this one?

import { app, BrowserWindow} from "electron";
import * as path from "path";
// import * as url from "url";
const serve = require('electron-serve');

let mainWindow: Electron.BrowserWindow | null;

const loadURLs = serve({directory: path.join('file:///', __dirname, "../build/index.html")});

  async function createWindow() {
  await app.whenReady();
  // Create the browser window.electron
  mainWindow = new BrowserWindow({
    height: 600,
    webPreferences: {
      webSecurity: false,
      preload: path.join(__dirname, "preload.js"),
    },
    width: 1400,
  });
  console.log(path.join('://-', __dirname, "../build/index.html"));
  console.log('LoadUrl', {loadURLs});
  
  await loadURLs(mainWindow.loadURL(path.join('://', __dirname, "../build/index.html")));  

  mainWindow.webContents.on('did-start-navigation', () => {
    //if()
    // mainWindow.loadFile(path.join(__dirname, "index.html#/user/login"));
    // mainWindow.loadFile(path.join(__dirname, "index.html#/"));
  });

  // Open the DevTools.
  mainWindow.webContents.openDevTools();

  // Emitted when the window is closed.
  mainWindow.on("closed", () => {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null;
  });
  
}```

Look what I'm doing here. :)

Delayed protocol registration

If loadURL is used in app.on('ready', ...), it fails.

The protocol is registered after app.whenReady(), which is resolved after app:ready event.
(Tested in electron v3.1.9 & v5.0.1)

A failing test case can be generated by changing app.whenReady() to app:ready

Should not fallback to index.html when the non-existent path has an extension

Issuehunt badges

And the extension is not .html.

Loading index.html on these requests, makes it really hard to debug problems.


IssueHunt Summary

hadeeb hadeeb has been rewarded.

Backers (Total: $40.00)

Submitted pull Requests


Tips


IssueHunt has been backed by the following sponsors. Become a sponsor

Can't serve React static files

Error

{ Error: ERR_FAILED (-2) loading 'app://-'
at rejectAndCleanup (C:\Users\david\AppData\Roaming\npm\node_modules\electron\dist\resources\electron.asar\browser\navigation-controller.js:72:21)
at WebContents.stopLoadingListener (C:\Users\david\AppData\Roaming\npm\node_modules\electron\dist\resources\electron.asar\browser\navigation-controller.js:113:9)
at WebContents.emit (events.js:194:13) errno: -2, code: 'ERR_FAILED', url: 'app://-' }

What did i do

const loadURL = serve({ directory: "./build" });

app.on("ready", async () => {
  win = new BrowserWindow({
    width: 800,
    height: 600,
    title: "POSine",
    autoHideMenuBar: true,
    show: false,
    webPreferences: {
      nodeIntegration: true
    }
  });
  win.maximize();
  await loadURL(win)
    .then(data => {
      console.log(data);
    })
    .catch(error => {
      console.log(error);
    });

  win.on("closed", () => {
    win = null;
  });
});

what I spected

a window with the static files

what i actually got

a blank window with the error above in the terminal

Please if someone could help me with this

Create a new BrowserWindow in the Nuxt app.

I have created a nuxt.js and electron app which uses electron-serve 's loadURL method to load a page into the BrowserWindow. So far, I only have one BrowserWindow, which is the main window of the application and I'm able to perform page routing in this window like I would in a normal nuxt web application. But I want to create a second application window and I'm not sure how to use the loadURL to load a page into the secondary window since any page you create in nuxt have a ".vue" extension.

ERR_CONNECTION_REFUSED when starting node server from sveltekit

Hi,

I'm have a Sveltekit application that I want to run inside electron. I choose the option to export my svelte kit application into node application. It works perfectly when running it with node build-folder. But when starting it inside electron the node server does not startup.

Removing tthe hostname and scheme will response in a ERR_FILE_UNKNOW error.

import { app, BrowserWindow } from 'electron';
import serve from 'electron-serve'

const loadURL = serve({
  directory: 'build',
  hostname: '0.0.0.0:3000',
  scheme: 'http'
});
let mainWindow;

(async () => {
	await app.whenReady();

	mainWindow = new BrowserWindow();

	await loadURL(mainWindow);

})();
npx electron-forge start -l   
✔ Checking your system
✔ Locating application
⠋ Loading configuration
✔ Locating application
✔ Loading configuration
✔ Preparing native dependencies [0.1s]
✔ Running generateAssets hook
⠋ [plugin-vite] Launching dev servers for renderer process code
◼ [plugin-vite] Compiling main process code
✔ [plugin-vite] Launching dev servers for renderer process code [0.0s]
⠋ [plugin-vite] Compiling main process code
vite v5.1.6 building for development...

watching for file changes...
vite v5.1.6 building for development...
✔ [plugin-vite] Launching dev servers for renderer process code [0.0s]
⠙ [plugin-vite] Compiling main process code

build started...

build started...
✓ 1 modules transformed.
Generated an empty chunk: "preload".
✓ 1 modules transformed.
.vite/build/main.js  0.62 kB │ gzip: 0.33 kB
built in 25ms.
✔ [plugin-vite] Launching dev servers for renderer process code [0.0s]
✔ [plugin-vite] Compiling main process code [0.0s]

(node:11662) electron: Failed to load URL: http://0.0.0.0:3000/ with error: ERR_CONNECTION_REFUSED
(Use `Electron --trace-warnings ...` to show where the warning was created)
(node:11662) UnhandledPromiseRejectionWarning: Error: ERR_CONNECTION_REFUSED (-102) loading 'http://0.0.0.0:3000/'
    at rejectAndCleanup (node:electron/js2c/browser_init:2:74086)
    at WebContents.failListener (node:electron/js2c/browser_init:2:74299)
    at WebContents.emit (node:events:514:28)
(node:11662) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
[11662:0319/131328.898771:INFO:CONSOLE(2)] "%cElectron Security Warning (Insecure Content-Security-Policy) font-weight: bold; This renderer process has either no Content Security
  Policy set or a policy with "unsafe-eval" enabled. This exposes users of
  this app to unnecessary security risks.

For more information and help, consult
https://electronjs.org/docs/tutorial/security.
This warning will not show up
once the app is packaged.", source: node:electron/js2c/sandbox_bundle (2)

app scheme not working on packaged app

Hi,

working with electron-serve on an electron 6 app everything works well on dev environment.

I'm trying to run the packaged app (electron builder) on windows 10 but the app schema/protocol registered by electron-serve is not understood by windows and it's trying to search for an external application capable to open it on the windows store.

Sans titre
you need a new application to open this link app
Search an application on the Microsoft Store

The result is a white screen =(

Is there any manipulation to do on production environment to avoid this?

Implement how to serve two windows

It is not possible (is it? I've been trying for a while now and have concluded it is not) to serve two different directories when the electron app has two windows.

Something like this

const loadURLOne = serve({ directory: 'one' })
const loadURLTwo = serve({ directory: 'two' })

function createWindow() {
  const oneWindow = new BrowserWindow({
    width: 1800,
    height: 1600,
  })

  const twoWindow = new BrowserWindow({
    width: 1800,
    height: 1600,
  })

  if (isDev) {
    oneWindow.loadURL('http://localhost:3000/one')
    twoWindow.loadURL('http://localhost:3000/two')
  } else {
    loadURLOne(oneWindow)
    loadURLTwo(twoWindow)
  }

This in dev works as expected (the localhost is an astro site)
But in build I can only get two windows opened that point to the same directory (the first one).

So this would be a nice feature to have in mind, if it is feasible.

EDIT: Or a variant would be to point, instead of a directory, to a file

const loadURLOne = serve({ directory: '.', file: 'index.html' })
const loadURLTwo = serve({ directory: '.', file: 'two.html' })

Using it with electron builder ?

Hi, I try to build using electron builder, and after build, it seems cannot open the 'app://-' location, is it because the
"build" folder that contains single-page web app files is not accessible ?

My electron builder config :

  ...
  "build": {
    "extraFiles": [
      "build"
    ],
  ...

the "build" folder is the single-page web app folder

Anybody has clue ?

Thanks

how to handle cors at production mode ?

if (isProd) serve({ directory: 'app' });
else app.setPath('userData', `${app.getPath('userData')} (development)`);

(async () => {
    await app.whenReady();

    mainWindow = createWindow('main');
    if (isProd) mainWindow.loadURL('app://./home.html');
    else {
        const port = process.argv[2];
        console.log(this.state.port);
        mainWindow.loadURL(`http://localhost:${port}/home`);
    }
            ...
})();

==================================================
The above is my code snippet, in production mode, reporting cross-domain issues

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.