I want to use pywebview in Python to make an app using HTML/JavaScript, potentially large, so I would like to keep separate files, index.html and index.js for ease of management.
For purpose of question, the simple codes for html & js are used as below. This html can be loaded on a browser and JS function works perfectly (to highlight a text when I click on the button).
I could load the html using pywebview (code below). However, nothing happened when I click the button. I have tried several things but no success:
- read content of index.js and put it as input for
window.evaluate_js(js_content)
- read content of index.html and put it as input for
window.evaluate_js(html_content)
- copy & paste content of index.js directly as (text) input for
window.evaluate_js(<text_js>)
Any hints or solutions are appreciated!
index.html
<!DOCTYPE html>
<html>
<body>
<h1>My First JavaScript</h1>
<p id="demo">JavaScript can change the style of an HTML element.</p>
<script src="index.js"></script>
<button type="button" onclick="myFunction()">Click Me!</button>
</body>
</html>
index.js
function myFunction() {
document.getElementById("demo").style.fontSize = "25px";
document.getElementById("demo").style.color = "red";
document.getElementById("demo").style.backgroundColor = "yellow";
}
app.py (I left the code in comment for the 3 options I tried, as explained above)
import webview
def evaluate_js(window):
with open('index.html', 'r') as f:
html = f.read()
# with open('index.js', 'r') as f:
# js = f.read()
result = window.evaluate_js(
html
# js
# function myFunction() {
# document.getElementById("demo").style.fontSize = "25px";
# document.getElementById("demo").style.color = "red";
# document.getElementById("demo").style.backgroundColor = "yellow";
# }
)
print(result)
with open('index.html','r') as f:
html = f.read()
if __name__ == '__main__':
window = webview.create_window('Run custom JavaScript', html=html)
webview.start(evaluate_js, window)