I am trying to call a Javascript function using C# in Content Grabber. (Content Grabber is a web scraping software).
The Javascript code is this:
$.definePage({
idRecaptcha: null,
init: function() {},
carregarReCaptcha: function() {
if(page.idRecaptcha == null) {
var sitekey = $("#reCaptchaPublicKey").val();
page.idRecaptcha = grecaptcha.render($("#tecRecaptcha")[0], {
'callback' : page.verifyCallback,
'sitekey': sitekey
});
}
},
verifyCallback: function(response) {
if(response) {
$("#form").submit();
}
}
});
var onloadCallback = function() {
page.carregarReCaptcha();
}
The function I want to call is "verifyCallback". This function essentially submits the recaptcha token, which will verify if the token I have entered is correct or not.
In my Content Grabber agent, I want to call this function, and I have this code, but it's giving me an error:
using System;
using System.Web.UI;
using Sequentum.ContentGrabber.Api;
public class Script
{
//See help for a definition of CustomScriptArguments.
public static CustomScriptReturn CustomScript(CustomScriptArguments args)
{
// retrieve page from current handler
var page = System.Web.HttpContext.Current.CurrentHandler as Page;
if (page == null)
{
// do something, e.g. throw exception
return CustomScriptReturn.Pause();
}
// Place your script code here.
// Return empty for no special action.
string response = args.DataRow["Captcha"];
string script = "page.verifyCallback('" + response + "');";
// call ClientScript from existing page instance
page.ClientScript.RegisterStartupScript(page.GetType(), "page.verifyCallback", script, true);
return CustomScriptReturn.Empty();
}
}
When I compile it, it's returning this error:
Object reference not set to an instance of an object.
It looks like I can't just delete object sender, EventArgs e
I'm not really familiar with JS or C#, so I would appreciate any help I can get. Thank you so much!
The problem occurs because you're trying to use
ClientScript
instance from a class which not inherited fromSystem.Web.UI.Page
(base class for code-behind pages). As long as you have access toHttpContext.Current
, you can retrievePage
instance from its handler property (i.e.CurrentHandler
) and useClientScript
as in example below:Update:
As for explaining the second error after edit, it occurred because you're declaring a method named
callback
insideCustomScript
method, which is not valid (and thereturn
statement must be on the last). If thesender
andEventArgs
handlers are unnecessary then simply omit them. Here is an example to properly returnCustomScriptReturn
:Related issue:
An object reference is required for the non-static field, method, or property 'System.Web.UI.Page.ClientScript.get'