Search code examples
javascriptc#chromiumchromium-embeddedcefsharp

Inject JavaScript to website


I'm trying to inject JavaScript code to a website and run this function:

    String js = "var script = document.createElement('script');" +
    "script.type = 'text/javascript';" +
    "script.text = \"function myFunction() { " +
       "return 'test method';" +

    "}\";" +
    "(document.head || document.body || document.documentElement).appendChild(script);";
    chromeBrowser.ExecuteScriptAsync(js);
    chromeBrowser.EvaluateScriptAsync("myFunction();");

It's a simple code that return text.

When i try to inject it and call myFunction i get this error message:

Uncaught ReferenceError: myFunction is not defined @ about:blank:1:0

Solution

  • Since you're using Async methods could it be that myFunction isn't yet defined but will be soon?

    Try this:

    chromeBrowser.EvaluateScriptAsync("setTimeout(myFunction, 100);");