问题
I'm playing around with Electron and want to do the following:
- Use
BrowserWindow.loadURL()to openurl_1 - In the UI part of
url_1thatBrowserWindowrenders, there's a link which points to another resource, let's sayurl_2.html - When I click this link, normally my
BrowserWindowwould loadurl_2.html. However, I want myBrowserWindownot to actually go to loadurl_2.htmlfrom the internet, since I actually have another file, say,url_3.htmlin my app's resources. What I want to achieve is this: WhenBrowserWindowdetects thaturl_2.htmlis going to be loaded, it will automatically loadurl_3.html.
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?
回答1:
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.
来源:https://stackoverflow.com/questions/57479171/how-to-hook-a-target-url-with-my-own-resources-in-electron