How can I execute javascript function in C# or WPF

2019-07-25 08:03发布

问题:

I'm using C# .net 4.5 with VS2015 and try to do scraping the website. HTML table to data. For the web browser control using winform C# one, because I heard that one has more feature than WPF control.

Here's the website which I try to parse. (Korean music streaming site like apple music) http://www.melon.com/mymusic/like/mymusiclikesong_list.htm?memberKey=7605160 and there's a script for turning the page as shown below.

javascript:pageObj.sendPage('21');

that means to show the data table since 21 of the data list. but I don't know how to run that script inside of my C# webbrowser. I tried to run with InvokeScript with parameters but it couldn't find the script. As far as I've heard in order to execute object wrapped function, I can inject a function inside of loaded HTML document like a proxy. but it failed as well. After many attempts, I've noticed the function can be executed by chrome console(F12) just easily. Is there any source snippet or 3rd party library to run javascript in C# just like chrome console? or even if I have to implement it, please give me any tips.

回答1:

The javascript:pageObj.sendPage('21'); is a url which you can navigate to. The web-browser doesn't actually navigate to the script, instead it executes the script. So you can simply use Navigate method of WebBrowserControl:

this.webBrowser1.Navigate("javascript:pageObj.sendPage('21');");


回答2:

I invoke javascript via web browser control of WPF by the below command:

string ScriptName = "sendPage";
string ID = "21";
this.WebBrowserPage.InvokeScript(ScriptName, ID);