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


#1
  • 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:
protocol.registerStandardSchemes(['webexpress'])
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"
        }
        console.log(request);
        callback({
            path: path.normalize(`${__dirname}/${url}`)
        })
    }, (error) => {
        if (error) console.error('Failed to register protocol')
    })
    createWindow();
});

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

$.ajax({
    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


#2

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


#3

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


#4

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.


#5

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


#6

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).


#7

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