ClientScript not working properly on class C# - javascript

I want to deploy a script on C# which usually uses methods like:
ClientScript.RegisterStartupScript(GetType(), "script", "Details('" + hdnId.Value + "');", true);
However I wanted to make a class that runs that code:
public class WebUtilities
{
public static void CustomScript(Page objPage, string strScript)
{
objPage.ClientScript.RegisterStartupScript(objPage.GetType(), "script", strScript, true);
}
}
When I call WebUtilities.CustomScript, sometimes it works, but leaves a //]]> at the bottom of the page.
And there is one occasion that it does not work at all. I only noticed that the first method works, and the second one doesn't.
How can I make the class version to work properly?

I have this function, and it always works, try it
public static void callJavascriptFunction(string strScript)
{
if (HttpContext.Current == null && HttpContext.Current.Handler is Page) { return; }
Page currentPage = (Page)HttpContext.Current.Handler;
ScriptManager.RegisterStartupScript(currentPage,
currentPage.GetType(),
"Funct",
strScript,
true);
}

Related

Waiting for element visibility instead of page load with Neustar WPM

I am trying to write a Neustar WPM script to measure the time taken from clicking a button to the appearance of a button in a overlay that opens. The script looks something like below.
var webDriver = test.openBrowser();
var selenium = webDriver.getSelenium();
webDriver.get('https://www.mywebsite.com');
selenium.waitForPageToLoad(30000);
// Start logging HTTP traffic and timings
test.beginTransaction(); 
test.beginStep("Open SignUp");
selenium.click("link=Sign Up");
selenium.waitForElementPresent("name=nextStep");
test.endStep();
test.endTransaction();
The problem I am facing is that click does not return immediately and waits for the overlay to completely load. However I want to stop as soon as desired element is visible. How can I ensure that selenium.click return immediately instead of waiting till entire page is loaded.
you can try using this Java method,
public WebElement waitForVisibilityOfElementLocatedBy(final By locator) {
return waitFor(visibilityOfElementLocated(locator));
}
public static ExpectedCondition<WebElement> visibilityOfElementLocated(final By locator) {
return new ExpectedCondition<WebElement>() {
public WebElement apply(WebDriver driver) {
try {
return ExpectedConditions.elementIfVisible(ExpectedConditions.findElement(locator, driver));
} catch (StaleElementReferenceException var2) {
return null;
}
}
public String toString() {
return "visibility of element located by " + locator;
}
};
}`

Android Webview - detect jquery document ready

I use an Android Webview to convert a website to an android app. The website uses many JavaScript files and many of them start at $(document).ready(). The website works great, but the app recognizes only the $(document).ready() from the first file. "console.log("anything");" placed on second file run only if it is outside of $(document).ready().
// Java
private void javaRun(String script)
{
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
myWebView.evaluateJavascript(script, null);
} else {
myWebView.loadUrl(script);
}
}
#Override
public void onPageFinished(final WebView view, String url) {
super.onPageFinished(view, url);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
javaRun("javascript:ready();");
}
}, 200);
}
// Javascript
function ready()
{
$('li').click(function(){
$(this).toggleClass('read');
});
}

Redirect to a page after a pop up opens

I am trying to redirect a web page after a condition is returned as true but I can't seem to get it work. In theory this should, shouldn't it. What am I missing, is it even possible!
protected void btnVerify_Click(object sender, EventArgs e)
{
if (value == txtVerification.Text || txtVerification.Text == "****")
{
//defines a bool to tell if the popup window has been shown, this will only ever return true
bool PopupShown = doRedirect();
if(PopupShown)
{
Response.Redirect("somewebpage.aspx");
}
}
else
{
lblVerificationFailed.Visible = true;
}
}
//Opens the popup window to fire off the download and returns true
bool doRedirect()
{
string url = "GetDocs.aspx";
string s = "window.open('" + url + "', 'GetDocs', 'height=150,width=300,left=100,top=30,resizable=No,scrollbars=No,toolbar=no,menubar=no,location=no,directories=no, status=No');";
ClientScript.RegisterStartupScript(this.GetType(), "script", s, true);
return true;
}
You are trying to do in the server things that can be much more easily done on the client side.
You're using a server event to catch the click of a button on your view, launch a client popup and later redirect your page execution.
Try with something like this on javascript:
var btnVerify = document.getElementById("btnVerify");
btnVerify.addEventListener("click", function() {
window.open('GetDocs.aspx', 'GetDocs', 'height=150,width=300,left=100,top=30,resizable=No,scrollbars=No,toolbar=no,menubar=no,location=no,directories=no, status=No');
window.location.href = "somewebpage.aspx";
});
Sussed it, if I use window.location.replace instead of window.location it works exactly like I want it to. Many thanks all :)

Null reference from control after page loads

I am trying to run a piece of javascript after the page loads:
protected void Page_LoadComplete(object sender, EventArgs e)
{
if (IsPostBack)
{
string controlName = getPostBackControlName();
if (controlName == "btnSubmit" || controlName == "ddlSalary")
{
Page.ClientScript.RegisterStartupScript(GetType(), "myAlertScript", "onLoadDisplay(this)", true);
}
}
}
Here is the referenced javascript:
function onLoadDisplay(sender) {
PerDiemClicked(sender);
}
function PerDiemClicked(sender) {
if (document.getElementById('<%= chkbxPerDiem.ClientID %>').checked == true) {
document.getElementById("PerDiemDisplay").style.display = 'inline';
}
else {
document.getElementById("PerDiemDisplay").style.display = 'none';
}
}
I'm getting this error:
0x800a138f - JavaScript runtime error: Unable to get property
'checked' of undefined or null reference
I dont understand why the checked is coming back null because I am waiting for the page to complete postback before checking. How do I check this control and run the above code correctly?
edit: here is the checkbox:
<asp:CheckBox ID="chkbxPerDiem" runat="server" Checked="false" onclick="PerDiemClicked(this)" />
Your script likely executed before chkbxPerDiem was added to the DOM. Perform your script in the window load event:
window.addEventListener("load", function() {
onLoadDisplay(this);
});
Try this:
Page.ClientScript.RegisterStartupScript(GetType(), "myAlertScript", #"
window.addEventListener('load', function() {
onLoadDisplay(this);
});", true);
See this answer
Here is how I solved it.
This code does in fact post after page load:
protected void Page_LoadComplete(object sender, EventArgs e)
{
if (IsPostBack)
{
string controlName = getPostBackControlName();
if (controlName == "btnSubmit" || controlName == "ddlSalary")
{
Page.ClientScript.RegisterStartupScript(GetType(), "myAlertScript", "window.addEventListener('load', function() { onLoadDisplay(this); });", true);
}
}
}
I had to modify the javascript function to check if it exists before checking whether its checked:
function PerDiemClicked(sender) {
if (document.getElementById('<%= chkbxPerDiem.ClientID %>') != null) {
if (document.getElementById('<%= chkbxPerDiem.ClientID %>').checked == true) {
document.getElementById("PerDiemDisplay").style.display = 'inline';
}
else {
document.getElementById("PerDiemDisplay").style.display = 'none';
}
}
}
Thanks everyone.
Page_LoadComplete is a server-side event, and all server-side events will run before the page is even sent to the browser. Remember, these server-side events are related to constructing the page. You need to run your JavaScript after the page has been constructed, served, and fully loaded by the browser. This means the Page_LoadComplete event runs long before your JavaScript code can run.
Page.ClientScript.RegisterStartupScript(GetType(), "myAlertScript", "onLoadDisplay(this)", true);
The code above registers a call to your JavaScript load function. But it will insert the call to that function at the top of your page. So it will run before the rest of the page is loaded.
You need to review how ASP.NET events work. Again, all of the server-side events run before the page is even sent to the browser. The JavaScript shouldn't run until after the browser has received and loaded the page.

Safari issue with HttpContext.User.Identity

I try to play mp3 file, which is returned by MyAudio method from ContentController, through html5 audio tag. Following code:
[Authorize]
public class ContentController : Controller
{
private ContentServices Content { get; set; }
protected override void Initialize(RequestContext requestContext)
{
if (requestContext.HttpContext.User.Identity.isAuthenticated)
{
base.Initialize(requestContext);
}
}
public ActionResult MyAudio(string name)
{
var file = Server.MapPath("~/" + name);
return File(file, "audio/mp3");
}
Common html code
When the user is Authorized all works perfect in Chrome. But when I have tested it in Safari there is a strange mystery. The HttpContext.User.Identity.isAuthenticated returns false and of course code doesn't execute further.
The interesting thing is that when I use for example #Html.Action or #Html.RouteLink, HttpContext.User.Identity.isAuthenticated will return true.
I've tried to use javascript and jquery to solve the problem, but I also had wierd things at Safari.
<script type="text/javascript">
function getAudio() {
if (audio.src == "" || audio.src == null) {
// (1) audio.src = '#Url.Content("~/Content/MyAudio")' + "hello.mp3";
// (2) audio.src = '#Url.Action("MyAudio", "Content", new { name = "hello.mp3" } )';
/* (3) $.get('#Url.Content("~/Content/MyAudio")', {"name": "hello.mp3"},
function(data) {
alert("hello");
});
*/
audio.load();
audio.play();
}
}
</script>
Both (1) and (2) have the same problem. But when I use (3), HttpContext.User.Identity.isAuthenticated returns true at Safary. But I guess u can't give file stream through jquery.
Have anyone have an idea what's is go on nad how I can fix the problem?
PS I use ASP.NET Development Server and Safari 5.1.7 Win32 7.

Categories

Resources