[Custom protocol] Can't access to file on C:/ with ajax

  • Electron version: 1.3.4
  • Operating system: Windows 10
    Hi, I’m writing my internet browser, and I need to read C:/userdata/history.json from custom protocol. It’s loading all resources like js and css files. My code to register custom protocol in main process:
app.on('ready', function() {
    protocol.registerFileProtocol('webexpress', (request, callback) => {
        var url = request.url.substr(13)
        var lastChar = url.substr(url.length - 1)
        var s = url.split("/");
        if (lastChar != "/") {
            url = url.replace(s[0], "")
        if (lastChar == "/") {
            url = url.substring(0, url.length - 1)
            url += ".html"
            path: path.normalize(`${__dirname}/${url}`)
    }, (error) => {
        if (error) console.error('Failed to register protocol')

code to history.js (webexpress://history)

    type: "GET",
    url: "/userdata/history.json",
    success: function(data) {

The error is Failed to load resource: net::ERR_FILE_NOT_FOUND: webexpress://history/userdata/history.json


Why aren’t you using the Node File System API to read the file directly?


The history.html file is rendering in webview and I can’t use node.js fs module.


You can access Node modules in the preload script, so your preload script can do something like:

const fs = require('fs');

global.getHistoryData = function () {
  return JSON.parse(fs.readFileSync('path/to/history.json'));

And your webview code can then call getHistoryData().

If you want to get this working with a custom protocol you’ll need to debug the main process to see if the callback you passed to registerFileProtocol() is being called, and if it’s building a valid resource path.


Thank you very much @enlight, but when I call global.getHistoryData(); in history.js I’m getting an error:
Uncaught ReferenceError: global is not defined


When you call getHistoryData() in the webview don’t prefix it with global (you only need the prefix when you define the function in the preload script).


Oh nice! Thank you very much! Problem solved :slight_smile: