3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

pywebviewをちょっと便利に使う

Posted at

python側からjs側に作用したい

js側にファンクションを用意せずにpython側からjsスクリプトを実行したい場合、evaluate_jsでpython側からjs側に作用は出来るのですがwindowを指定する必要があるのでどこかのタイミングでAPIにwindowを渡しておく必要があります。
のでwindowをapiに渡すために以下のようにしてみます。

api = Api()
api.window = ...

これによってApiクラスの中ではself.windowで参照することが可能になります。

※本来はjs側からAPIが呼び出されてそのレスポンスとして動作するのが正しいと思うし、もっと正しいやり方があるのかもしれませんがー

動作する一通りのコード

pywebview自体はpipでインストールしておくこと。

webview_test.py
import webview

"""
Windowとやり取りするためのApiクラス
"""
class Api:
    def __init__(self):
        self.window = None

    # windowに対してevaluateしてjsを実行できる。
    def hello(self):
        self.window.evaluate_js(
            """
            console.log("hello debug!");
            """
            )
"""
この部分はウィンドウの動作とは別に動作する
"""
def threadFunction(window):
    print(window)

"""
Windowの生成等
"""
def main():
    with open("html/index.html", "r", encoding="utf-8") as fr:
        html = fr.read()

    api = Api()
    #apiクラスにwindowを渡しておくことで後から利用しやすくする
    api.window = webview.create_window(title = "Test App",
                                       html = html,
                                       js_api = api,
                                       width = 600,
                                       height = 400)

    webview.start(threadFunction, api.window, debug=True)

if __name__ == "__main__":
    main()
html/index.html
<!DOCTYPE html>
<html>
	<head>
		<title>Test</title>
	</head>

	<body>
		<h1>WebViewTest</h1>
		<p>this is webview window</p>
		<button id="exec">Button!</button>
	</body>

	<script>
		<!--ドキュメントが準備出来次第いろいろする-->
		window.addEventListener("pywebviewready", function() {
			<!--buttonにイベントを追加python側のAPIを呼び出す-->
			document.getElementById("exec").addEventListener("click", function(){
				pywebview.api.hello();
			})
		})
	</script>
</html>

とりあえずの〆

webviewをpythonから利用できるということで便利なはずなのですが、いまいち使われていない様な気もします。

今回はやっていませんが、python側からDOMを操作するようにすればリアルタイムにコンテンツを変更してゆくようなものも作れますし、そういった便利な機能をまとめておけば便利に使えると思います。

画面遷移やダイアログ関係あたりが気になっているのでその辺りを次回探ってゆこうと思います。

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?