简体   繁体   中英

How to call a JavaScript function with parameters on C#

I want to call a JavaScript function with HttpWebRequest or WebRequest in C#. I don't want to use a webbrowser which I can call invokemember.

Here is my code:

public void MyWebRequest(string url, string method, string data)
{  

       request = WebRequest.Create(url);

        if (method.Equals("GET") || method.Equals("POST"))
        {
            // Set the Method property of the request to POST.
            request.Method = method;
        }
        else
        {
            throw new Exception("Invalid Method Type");
        }
       string postData = data;

        byte[] byteArray = Encoding.UTF8.GetBytes(postData);

        request.ContentType = "application/x-www-form-urlencoded";

        request.ContentLength = byteArray.Length;

        dataStream = request.GetRequestStream();

        dataStream.Write(byteArray, 0, byteArray.Length);

        dataStream.Close();
}
MyWebRequest("http://example.com", "POST", "javascript:onclick=\"try(1,3)\"");

try is a JS function which has two int parameters. I want to call the onclick method, but how can I pass parameters to the function.

onclick="try(1,3);"

Just so this isn't an open-ended question...

WebRequest is essentially a "glorified" socket library that establishes a connection to and from a web server. It's not more than a means to transfer data between a client (the app using the WebRequest ) and the server hosting the site.

For the same reason if you viewed the dataStream (referencing your code) you'd only see HTML markup and not actual layout elements and colors, styles, etc., javasript also won't work. HTML needs a rendering agent, JavaScript needs an engine.

So, if you need the ability to use JavaScript included on the page, WebBrowser is your best bet. It will load up any libraries/plugins necessary to run any JavaScript found on the page. It may be slower, yes, but that's because it's giving you a lot more than just transferring data (it's also rendering HTML, executing any initialization scripts, and binding to any elements that the page has defined to be necessary for the aesthetics.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM