Files
pywebview/docs/examples/js_api.md
Roman 0698b059db pywebview 3.0 (#340)
* Update change_url.md

* Update api.md

* Update installation.md

* Add Google Analytics

* Fix installation

* 2.4 info

* [Docs] add information about window.pywebview availability

* Update debuggig info about QTWebEngine

* [Docs] Add information about app architecture

* Update cef.md

* [CEF] Fix JS logic not persisting after navigating to another page

* #169 Frameless window (#313)

* Merge PR #177: [Cocoa] Implement frameless windows

* [All] Add skeleton for `frameless` parameter
* [Cocoa] Add `frameless` kwarg to remove the window frame.
  - Implement a DragBar class to enable dragging the webview
  - Make the drag bar stick to the top and autoresize to the width
    of the view.

* [WinForms] Implement frameless window + easy drag

* Merge PR #177: [Cocoa] Implement frameless windows

* [All] Add skeleton for `frameless` parameter
* [Cocoa] Add `frameless` kwarg to remove the window frame.
  - Implement a DragBar class to enable dragging the webview
  - Make the drag bar stick to the top and autoresize to the width
    of the view.

* [WinForms] Implement frameless window + easy drag

* [GTK] partial implementation of frameless window

* [QT] Partial implementation of frameless window

* [QT] implement easy drag

* [Cocoa] Hide standard buttons and make the entire window draggable

* [GTK] implement easy move

* Add frameless tests

* Remove unused parameter

* [Cocoa] Implement free drag

* Revert WebBrowserInterops

* Code cleanup

* Update interop DLLs

* Fix interop dll

* Update docs; Fix tests

* Add example

* Update examples

* [CEF]: Implement support for pyinstaller one-file mode

* [CEF] Fix typo

* [All] Change api_call timeout to 15 seconds

* Update setup.py

* [QT] Simplify QT installation

* New API
Cocoa implementation
Revamped tests and examples

* Fix web engine force setting

* Rename destroy_window to destroy

* Update documentation

* Add documentation for 2.4

* Refactor project structure

* [GTK] New API support

* Rename confirm_quit to confirm_close
Split lifecycle events to shown and loaded

* [GTK] Implement new API
Fix tests

* [QT] New API implementation

* Remove multiprocessing

* [Windows/CEF] New API implementation

* Implement CSRF token
[All] Implement get_element

* Update Flask app example

* Rename get_element to get_elements. Bug fixes.

* [GTK] Implement propert JS-Python bridge for WebKit2 >2.2

* Update documentation

* [Windows/CEF] New API implementation

* Add token test

* [Winforms] Fix js api initialization

* [Cocoa] Fix events

* Debug: print webkit version

* [GTK] Check for old webkit

* [GTK] Fix event issues

* Catch notimlementederror in tests

* Update travis conf with qt from pip

* Update .travis.yml

* Update .travis.yml

* Update .travis.yml

* Update .travis.yml

* Update .travis.yml

* [Windows] Preliminary implementation of EdgeHTML based on PR from @HeavenVolkoff

* [docs] Add information about EdgeHTML

* EdgeHTML WIP

* Remove windows.web import

* EdgeHTML improvements. Fix MSHTML evaluate_js

* [Docs] Add information about renderer limitations

* [EdgeHTML] Fix bugs and tests

* Remove window from windows list after it is destroyed

* Fix window object deletion after window is closed via GUI

* [Docs] Add information about renderer codes

* Refactor and fix JS API
Remove multiprocessing example
[MSHTML] Add console.log debug support

* [Travis] Change conf

* [WinForms] Fix fullscreen

* Fix dll installation

* [Windows] Fix DLL bundling

* Update changelog

* [CEF]: Fix JS API

* Update changelog

* Built-in HTTP server implementation

* Add http server test

* Add http server testcd

* Add http server testcd

* [EdgeHTML] allow localhost urls

* Add video example

* Bug fixing

* [Cocoa] Remove media prefs

* Update .travis.yml

* Update .travis.yml

* Update .travis.yml

* [Travis] Disable QT 5.12 builds

* Update html_load.md
2019-07-07 13:33:37 +03:00

3.5 KiB
Executable File

Javascript API

Create an application without a HTTP server. The application uses Javascript API object to communicate between Python and Javascript.

import threading
import time
import sys
import random
import webview


html = """
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">

<style>
    #response-container {
        display: none;
        padding: 3rem;
        margin: 3rem 5rem;
        font-size: 120%;
        border: 5px dashed #ccc;
    }

    label {
        margin-left: 0.3rem;
        margin-right: 0.3rem;
    }

    button {
        font-size: 100%;
        padding: 0.5rem;
        margin: 0.3rem;
        text-transform: uppercase;
    }

</style>
</head>
<body>


<h1>JS API Example</h1>
<button onClick="initialize()">Hello Python</button><br/>
<button id="heavy-stuff-btn" onClick="doHeavyStuff()">Perform a heavy operation</button><br/>
<button onClick="getRandomNumber()">Get a random number</button><br/>
<label for="name_input">Say hello to:</label><input id="name_input" placeholder="put a name here">
<button onClick="greet()">Greet</button><br/>

<div id="response-container"></div>
<script>
function showResponse(response) {
    var container = document.getElementById('response-container')

    container.innerText = response.message
    container.style.display = 'block'
}

function initialize() {
    pywebview.api.init().then(showResponse)
}

function doHeavyStuff() {
    var btn = document.getElementById('heavy-stuff-btn')

    pywebview.api.doHeavyStuff().then(function(response) {
        showResponse(response)
        btn.onclick = doHeavyStuff
        btn.innerText = 'Perform a heavy operation'
    })

    showResponse({message: 'Working...'})
    btn.innerText = 'Cancel the heavy operation'
    btn.onclick = cancelHeavyStuff
}

function cancelHeavyStuff() {
    pywebview.api.cancelHeavyStuff()
}

function getRandomNumber() {
    pywebview.api.getRandomNumber().then(showResponse)
}

function greet() {
    var name_input = document.getElementById('name_input').value;
    pywebview.api.sayHelloTo(name_input).then(showResponse)
}

</script>
</body>
</html>
"""


class Api:
    def __init__(self):
        self.cancel_heavy_stuff_flag = False

    def init(self, params):
        response = {
            'message': 'Hello from Python {0}'.format(sys.version)
        }
        return response

    def getRandomNumber(self, params):
        response = {
            'message': 'Here is a random number courtesy of randint: {0}'.format(random.randint(0, 100000000))
        }
        return response

    def doHeavyStuff(self, params):
        time.sleep(0.1)  # sleep to prevent from the ui thread from freezing for a moment
        now = time.time()
        self.cancel_heavy_stuff_flag = False
        for i in range(0, 1000000):
            _ = i * random.randint(0, 1000)
            if self.cancel_heavy_stuff_flag:
                response = {'message': 'Operation cancelled'}
                break
        else:
            then = time.time()
            response = {
                'message': 'Operation took {0:.1f} seconds on the thread {1}'.format((then - now), threading.current_thread())
            }
        return response

    def cancelHeavyStuff(self, params):
        time.sleep(0.1)
        self.cancel_heavy_stuff_flag = True

    def sayHelloTo(self, params):
        response = {
            'message': 'Hello {0}!'.format(params)
        }
        return response


if __name__ == '__main__':
    api = Api()
    window = webview.create_window('API example', html=html, js_api=api)