wjxiz
wjxiz

Reputation: 163

How to hook a target URL with my own resources in electron?

I'm playing around with Electron and want to do the following:

I tried to step into "loadURL" in source code of Electron, but only got the following in node_modules/electron/electron.d.ts. There's no more JavaScript implementation.

/**
 * Same as webContents.loadURL(url[, options]). The url can be a remote address
 * (e.g. http://) or a path to a local HTML file using the file:// protocol. To
 * ensure that file URLs are properly formatted, it is recommended to use Node's
 * url.format method: You can load a URL using a POST request with URL-encoded data
 * by doing the following:
 */
loadURL(url: string, options?: LoadURLOptions): Promise<void>;

How can I implement my requirements using Electron?

Upvotes: 1

Views: 1676

Answers (1)

Alexander Leithner
Alexander Leithner

Reputation: 3432

Those .d.ts files are so-called "definition files", think of them like .h (header) files for C/C++ programs. Thus, you don't see any implementation.

Another approach which you could implement, given you have access to url_1.html, is to attach an event listener to all links pointing to url_2.html and change the link target to url_3.html, like so:

window.addEventListener ("load", () => {
    nodes = document.querySelectorAll ('a[href="url_2.html"]'); // (1)
    for (int i = 0; i < nodes.length; i++) {
        nodes[i].addEventListener ("click", (e) => {
            e.preventDefault ();
            window.location.href = "url_3.html";                // (2)
    }
});

Two things need adjustment here: (1) is where the exact URL of url_2.html needs to be inserted, namely exactly as it has been specified in the a elements, and (2) is where you need to insert the full URL to your (local) url_3.html.

On the other hand, if you don't have access to the url_1.html file, possibly because it is used on a server and cannot be modified because it is also used through "normal" browsers which need to load url_2.html, you can manipulate the navigation process from the Electron main thread, like so:

webcontents = win.webContents;
webcontents.on ("will-navigate", (e, url) => {
    if (url === "url_2.html") {              // (1)
        e.preventDefault ();
        webcontents.loadURL ("url_3.html");  // (2)
    }
});

The above assumes that your BrowserWindow object is named win. Also, you need to modify two things here also: (1) is where you will need to put the full, exact URL to your url_2.html, namely exactly how Chromium would load it, and (2) is where you need to put your full URL to url_3.html.

Upvotes: 1

Related Questions