Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send a post request with an Electron webview

I want to send a POST request with an Electron webview from the outer script. At the moment I just set the src attribute to trigger a page load, which sends a GET request:

<webview id="view">
<script>
document.getElementById('view').setAttribute('src', 'http://example.com/?foo=bar');
</script>

Is there any way to navigate the webview to a URL by sending a POST request? Maybe a method of the webview, instead of just hacking with the src?

like image 508
flori Avatar asked Dec 19 '22 21:12

flori


2 Answers

You can execute arbitrary code from within the webview context with .executeJavaScript.

Moreover your code has access to all browser built-in apis. Easiest would be to use fetch, with method set to post.

In your case (provided the webview has been already loaded; for example its .src has been set):

document.getElementById('view')
  .executeJavaScript('fetch("http://example.com/?foo=bar", {method: "post"});');

Some remarks:

  1. The origin of the request is controlled by .src of the webview.
  2. It seems that all default security policy are still used by webview - specifically you cannot make calls to http: from https:.
  3. It is bit painful to pass code as a string.
like image 152
artur grzesiak Avatar answered Dec 28 '22 11:12

artur grzesiak


Now there is a new <webview>.loadURL() method with a postData option in the docs. I haven't used it yet but it looks exactly like what I was looking for in the past.

It seems they added it as a feature in the meantime.

like image 30
flori Avatar answered Dec 28 '22 09:12

flori