Forum Archive

Eval_js

robertiii

For some reasons the code does not run.

newView = ui.WebView()
            newView.name = 'song'
            newView.frame = v['view1'].bounds
            newView.content_mode = ui.CONTENT_SCALE_ASPECT_FIT
            newView.load_url(displayItems[row]['itemURL'])
            newView.eval_js("setSong('<h3>Title of the Song</h3></br><p>Joy to the world, the Lord is come.</p>')")
            v['view1'].add_subview(newView)
            v.song = newView

And here is the Javascript.

function setSong(element){
    var div = document.getElementById("lyrics");
    div.innerHTML = element;
}
robertiii

If i call the function later with a button it works but not here...

JonB

load_url does not wait for the page to load.. you need to wait until the doc is loaded/ready.

robertiii

How would I do that? I wondered if that was the case

JonB

One way would be to poll (sleep, check loop) document.ready via eval_js, though if you check it too early it might show ready before it starts the load,
You could also sleep for a few seconds, and hope that is enough to handle varying network cinditions. The most robust way is to set webview_did_finish_load to set a threading.event.
https://forum.omz-software.com/topic/2380/returning-execution-to-main-thread-with-ui-webview/3.
for you, it would work a little differentlt, as you probably just want to wait to set the title, but don't necessarily need to stop execution. You could, to ensure that you set the song before presenting, but I guess it all depends on what you are doing.

w=ui.Webview()
w.ready_event=threading.Event() 
w.webview_did_finish_load=set_title
w.load_url(....)
def set_song(sender):
   self.webview_did_finish_load = None # maybe needed to prevent the evaljs from triggering this again
   w.eval_js('setSong(...)..')
   self.ready_event.set() #optional

w.ready_event.wait() #optional
robertiii

I have tried emplementing this and cannot get it to work.

robertiii

The file is actually a local file. Is there a way to edit the html file before adding it. Basically making the file a template

robertiii

I just used SimpleTemplate

mikael

You don’t need threading for this. Instead:

<body onload="window.location.href='http://loaded/';">

Then, in the webview_should_start_load method of the WebView’s delegate, check for the url and run any post-load evals.

if url.startswith('http://loaded/'):
  # Do something
  return False
return True
enceladus

Using jquery could be one possible solution. Here is an example using jquery.

https://gist.github.com/619e923059d7643841e6f889655d8bf1