MasterDevs / ChromeDevTools

.NET library to interact with the Chrome Debugger
MIT License
134 stars 90 forks source link

How Inject Javascript code into webpage and receive a return value #39

Open AlexanderG84 opened 5 years ago

AlexanderG84 commented 5 years ago

I can't understand how to inject a javascript code into the web page. Also how could I get a possible return from this script. I loaded the MasterDevs.ChromeDevTools Solution in C#.

Thanks

ststeiger commented 5 years ago
string javaScriptToExecute = @"document.getElementById(""result"").innerHTML";

CommandResponse<EvaluateCommandResponse> evalResponse = await chromeSession.SendAsync(new EvaluateCommand
{
    Expression = javaScriptToExecute,
    // ContextId = 123
});

if (evalResponse.Result.ExceptionDetails != null)
    System.Console.WriteLine(evalResponse.Result.ExceptionDetails);
else
    System.Console.WriteLine(evalResponse.Result.Result.Value);
AlexanderG84 commented 5 years ago

Thank you very much Ststeiger! Works well! But If I wanted to see the web page on chrome and the impact of javascript on the page, is it possible? first i set an index in every tag( with a script), and after, i set border color only for some index( with inject a second script).

TY

ststeiger commented 5 years ago

Sure, you can screenshot the page.

Full code in the sample program: https://github.com/MasterDevs/ChromeDevTools/blob/master/source/Sample/Program.cs

If you need to wait a little after the functions executed:

// System.Threading.Thread.Sleep(waitInterval);
await System.Threading.Tasks.Task.Delay(waitInterval);
AlexanderG84 commented 5 years ago

thanks for the answer. I'm already using the example code. But my idea is the interact with the browser and see the page in "realtime". while browsing normally on chrome, I would like to be able to send scripts with external buttons from the browser. For example, while browsing the chrome tab, I wish I could press a key that colors all the "form" tags. it's possible? sorry if i wasn't clear