Created
June 10, 2020 03:18
-
-
Save hamstu/b1f88ea486508111668df8d39e2d0ca1 to your computer and use it in GitHub Desktop.
Electron file:// intercept
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const path = require('path'); | |
const { protocol } = require('electron'); | |
/** | |
* This method is used to intercept file requests from the Electron | |
* BrowserWindow ensure we load the correct files. | |
* | |
* This allows us to intercept requests from the JavaScript that ask for | |
* resources with absolute paths, e.g., `/web_modules/react.js`. Without | |
* the intercept, Electron would attempt (and fail) to load from the | |
* system's root directory. | |
* | |
* The reason our JS code is making absolute requests is becuse it is bundled | |
* with Snowpack, which assumes we'll be serving our site from a server, | |
* where using absolute `/` paths would resolve normally. | |
*/ | |
module.exports = function interceptFileRequests(assetDirectory) { | |
if (!assetDirectory) { | |
throw new Error('`interceptRequests` must be passed a directory argument.'); | |
} | |
return protocol.interceptFileProtocol('file', (request, callback) => { | |
// Remove `file://` from URL/path - decode as well since it may be urlencoded | |
const url = decodeURIComponent(request.url.substr(7)); | |
// Get just the relative path | |
const rootDir = path.resolve(__dirname, '..'); | |
const requestedUrlRelative = url.replace(rootDir, ''); | |
// Now insert the path to the asset directory | |
const newPath = path.join(rootDir, assetDirectory, requestedUrlRelative); | |
callback({ path: newPath }); | |
}); | |
}; |
call this before app.on("ready"
protocol.registerFileProtocol("file", (request, callback) => {
const filePath = url.fileURLToPath(request.url.replace(/extras/, "static/extras"));
callback(filePath);
});
@aztack, thanks for the usage
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@hamstu Could you share how where exactly should I add this file in the Electron + Snowpack setup?