0

I have asked a question not too long ago on how to wait for a script to be executed by cefSharp before continuing my main program and I was advised to use await browser.EvaluateScriptAsync(...) this works fine when I am not using any EventHandler. But say that I want to wait for the Dom to be loaded before executing my script I would use the following event handler:

window.addEventListener('DOMContentLoaded', (event) => {
    console.log('DOM fully loaded and parsed');
});

What I want to do now is return true once the Dom is loaded (and return nothing before).This would theoretically allow my program to wait till the dom is loaded before the execution continues. So what I tried to do was the following :

    await browser.EvaluateScriptAsync( "
    function returnTrue() {
    return true;
    }

    function waitForDom(callback) {
    window.addEventListener('DOMContentLoaded', (event) => {
      console.log('hi');  
      callback();
    });

    waitForDom(returnTrue);
    "};

console.WriteLine("outside");

The expected output would be :

hi
outside

but what I get is :

outside
hi

This implies that my main program doesn't wait for the Dom to be loaded before continuing.

Why does this not work ?

abiday
  • 85
  • 6
  • 1
    Just evaluate your script in LoadingStateChange event in c# and the DOM should be ready see https://github.com/cefsharp/CefSharp/wiki/General-Usage#when-can-i-start-executing-javascript for an example. – amaitland Jul 26 '19 at 20:00
  • @amaitland really helpful answer like always, awesome! – abiday Jul 26 '19 at 21:48

1 Answers1

0

I think you are looking for this

$( document ).ready(function() {
    console.log( "ready!" );
});

https://learn.jquery.com/using-jquery-core/document-ready/

or if javascript only

window.onload = function () { alert("It's loaded!") }

https://stackoverflow.com/a/1033448/5517161

Mo D Genesis
  • 5,187
  • 1
  • 21
  • 32
  • Window on load doesn't work in my case since I only want the Dom to be loaded and not all the images etc. – abiday Jul 26 '19 at 13:36
  • and event if i try await browser.EvaluateScriptAsync("window.onload = function () { alert("It's loaded!"); return true; }"); the program doesnt seem to wait for the page to be loaded – abiday Jul 26 '19 at 13:49
  • Not sure how to use await/async with an event listener. Could you try to explain it ? – abiday Jul 26 '19 at 13:56