0

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)
nphaibk
  • 71
  • 7

1 Answers1

0

You cant import local files in HTML using pywebview, instead of importing file index.js into HTML, just use and insert HTML here

  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 24 '23 at 10:54