Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the <webview> methods in Electron

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>
like image 539
Sam Eaton Avatar asked Jun 10 '15 19:06

Sam Eaton


2 Answers

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.

like image 126
Sam Eaton Avatar answered Oct 22 '22 01:10

Sam Eaton


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.

like image 30
Shawn Rakowski Avatar answered Oct 21 '22 23:10

Shawn Rakowski