On the Electron <webview>
documentation there is a list of methods that you can use with the object. When I try to run any of the methods, none of them work. When I looked in inpect the properties of the <webview>
element in the inspector, it says that its prototype is webview
. (__proto__ : webview
)
It is in that prototype where all of the methods are stored. So my element should basically just inherit those methods from its prototype when I use those methods (e.g. myWebview.openDevTools()
).
However! when i use Object.getProptotypeOf(myWebview)
I get HTMLElement
, NOT webview
like it shows in the inspector.
Here is an example of my code:
<webview id="myWebview" src="path/to.file"></webview>
<script>
var myWebview = document.getElementById('myWebview');
console.log("myWebview: ",myWebview);
console.log("prototype: ",Object.getPrototypeOf(myWebview)); //=> HTMLElement
myWebview.openDevTools();
</script>
I discovered the issue and added an example to the Electron Documentation
The bottom line is that you need to add a listener to the webview that listens for when the webview element is ready:
webview.addEventListener("dom-ready", function(){
webview.openDevTools();
});
According to @Shwany, the webview's methods will be available when the did-start-loading
event is fired, however it may be better practice to wait until the webview element is completely ready using dom-ready
For a more detailed explanation:
When the window is initially rendering the DOM, the webview methods are not available. Initially, the prototype for the <webview>
element is still the generic HTMLElement
.
It as after the page renders that the <webview>
element begins loading and then its prototype is changed to the webview prototype (same name as the element). And when it gains access to the webview prototype, it gains access to all of the webview prototype methods.
The documentation for the webview says:
If you want to control the guest content in any way, you can write JavaScript that listens for webview events and responds to those events using the webview methods.
Keying off of this clue I was able to call openDevTools on the webview by using the following code:
<script>
var myWebview = document.getElementById('myWebview');
myWebview.addEventListener("did-start-loading", function (e) {
myWebview.openDevTools();
});
</script>
I am guessing the methods are not applied to the webview right away. I tried accessing them on document.readystate == "complete" but they still were not available. Hopefully binding to the event above will get you the functionality you need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With