How to execute javascript in specifci time in .cs? - c#

If i have script like this :
<script type="text/javascript" src="//www.gmodules.com/ig/ifr?url=http://hosting.gmodules.com/ig/gadgets/file/100080069921643878012/facebook.xml&up_useNewFB_p=1&up_showPopUp2_p=true&synd=open&w=320&h=500&title=Facebook&border=%23ffffff%7C3px%2C1px+solid+%23999999&output=js"></script>
and i wanna to execute this script in specific time in my .cs code how to do this?

string rowTestHide = #"<script type="text/javascript" src="//www.gmodules.com/ig/ifr?url=http://hosting.gmodules.com/ig/gadgets/file/100080069921643878012/facebook.xml&up_useNewFB_p=1&up_showPopUp2_p=true&synd=open&w=320&h=500&title=Facebook&
border=%23ffffff%7C3px%2C1px+solid+%23999999&output=js"></script>";
ClientScript.RegisterStartupScript(this.GetType(),"rowTest", rowTestHide);

Try out with following code,
Page.ClientScript.RegisterClientScriptInclude("MyScript", "<script type="text/javascript" src="//www.gmodules.com/ig/ifr?url=http://hosting.gmodules.com/ig/gadgets/file/100080069921643878012/facebook.xml&up_useNewFB_p=1&up_showPopUp2_p=true&synd=open&w=320&h=500&title=Facebook&border=%23ffffff%7C3px%2C1px+solid+%23999999&output=js"></script>");

The only real way to do this at the moment (without using something like SignalR) is to implement a polling system.
You will have to have an Ajax call, that makes a request to your server every xxx seconds, using something like:
window.setTimeout(function(){ /* do ajax request */ }, 5000);
Which would run every 5 seconds.
If the desired result comes back from the DB, you'll have to then programatically inject the required script block into your page.
take a look at this:
jQuery AJAX polling for JSON response, handling based on AJAX result or JSON content

Related

How do I inject javascript code via webview?

Basically what I want to do is this this but I can't seem to find something similar for webview XAML control. What I ultimately need to do, is capture an incoming json file from the webview. As is, I get a bad request from the server and unsupported file exception from the webview. I thought about injecting a javascript so that it would alert me, I could get the body of the incoming json and bypass all the errors.
There are two main things you can do:
Call functions programically
Inject any code by using the HTML string
Function Calling
You can use InvokeScript to call javascript functions.
If you have in a webpage with a script:
<script lang="en-us" type="text/javascript">
function myFunction() {
alert("I am an alert box!");
}
</script>
Then you can in C# call:
MyWebview.InvokeScript("myFunction", null);
Which will execute the script function myFunction.
Injecting Text
If you download the HTML page and all other needed files(using the Windows HttpClient), you can inject any code by manipulating and then Navigating to string.
Lets say you want to change the above script to add another function, "HelloWorld", then you can
Search the file for something you know will be there, such as: <script lang=\"en-us\" type=\"text/javascript\">
Using string manipulation, add the desired text, such as a function (but this can be anything)
Navigate to the String
The C# code:
string MyWebPageString = GetWebpageString(WebpageUri);
string ScriptTagString = "<script lang=\"en-us\" type=\"text/javascript\">";
int IndexOfScriptTag = MyWebPageString.IndexOf(ScriptTagString);
int LengthOfScriptTag = ScriptTagString.Length;
string InsertionScriptString = "function SayHelloWorld() { window.external.notify(\"Hello World!\");} ";
MyWebPageString = MyWebPageString.Insert(IndexOfScriptTag + LengthOfScriptTag + 1, InsertionScriptString);
MyWebview.NavigateToString(MyWebPageString);
The result will be that the navigated to Webpage will look like this:
<script lang="en-us" type="text/javascript"> function SayHelloWorld() { window.external.notify("Hello World!");}
function myFunction() {
alert("I am an alert box!");
}
</script>
Since the injection can be applied to any area, even the HTML, you should be able to figure something out.
Hope this helps. Good luck.
This answer was based on this MSDN blog

Create new Script within <div> from C# and Reload newly created Script

I would like to implement the following, which would appear to be fairly easy, but I have been searching for a working example without success.
i) I have an HTML Tag in an aspx Page with an identification:
<div id="demo" runat="server">
ii) This Tag contains the following Script Tag, which itself has an identification:
<script id="scriptdemo" type="text/javascript" src="http://www.myurl.com/myquery"></script>
iii) I have an AJAX call which calls a Server Function (which is working without any issue)
iv) From that Server Function, I would like to either modify the “src” Attribute of the Script, or create and insert a new script in the existing division with a new src if this solution is easier to implement.
v) After executing the Server Code contained within the Server Function, the flow is properly passed back to the client (here again, I do not have any issue with this process).
vi) Once back on the client, I would like to refresh/reload the newly created script (or updated src attribute) using JavaScript/AJAX (either standard Javascript or JQuery).
Would someone have a working example of such code?
Check out http://api.jquery.com/jQuery.getScript/
It's basically shorthand for $.ajax with datatype as "script". This will load a script file for you, and give you the chance to run a callback when it's done.
$.ajax({
url: "your/ServerMethodThatReturnsScript",
dataType: "script",
success: successCallback
});
becomes
$.getScript("your/ServeRMethodThatreturnsScript", function() { /* some success callback */ });
In the event you can't do this but CAN make an ajax call to your server, you can use the eval method to execute any string that is in the form of javascript:
eval("/*some javascript*/");

Load .NET Resources Client-Side on each request

I have the following JavaScript snippet:
<script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(ajaxBeginRequest);
prm.add_endRequest(ajaxEndRequest);
function ajaxBeginRequest(sender, args) {
$.blockUI({ message: '<h1><img src="/images/ajax_loading.gif" /> <%= MyNameSpace.SomeWhereElse.Shared.RandomLoadingMessage() %></h1>' });
}
function ajaxEndRequest(sender, args) {
$.unblockUI();
}
</script>
Right now the C# line runs at page load and gives me one random message, but it is constant through the page execution until the page is refreshed. What I'd like it to do is give me a different message on each ajax Request
Any suggestions for this?
You can make a ajax call to a web service (called script service) to get the message on each invocation. See this article where it explains how to call script services using ASP.NET generated proxies as well as using jquery methods. You can use either method.

How do I pass a list from aspx to javascript?

I have a list that I loop through to populate my table. I would like to pass a row of data to my javascript code at best. If not, I would like to pass the list and the id number to search for that row in the list. How can I do this?
<%foreach(var item in Model.NewList) { %>
<tr>
<td><%=item.EntryDate.ToShortDateString() %></td>
<td onmouseover="showDetailsHover(<%=item %>,<%=item.idNumber%>);"
onmouseout="hideDetailsHover();"><%=Html.ActionLink(item.idNumber,"SummaryRedirect/" + item.idNumber) %></td>
</tr>
<% } %>
You can use Json serialization to pass this data
http://json.codeplex.com/ - library for serialization
The concept of "passing a list from aspx to javascript" is a little hard to understand since your ASP.NET code runs on the server and javascript code runs in the browser. Because they exist in different domains, you can't simply "pass" a list from one domain to the other.
However, you have several options available:
Expose a web service that you can access from javascript. The web service can be responsible for providing the row of data so that javascript can understand it.
Put staticly formatted JSON data directly into your javascript function when your page loads. JSON is a format that javascript can understand. While technically this isn't "passing" a variable into a javascript function from ASP.NET, it is saying "Here's the data I want to run in my javascript function when/if it runs on the client."
The quickest way I can think of is this:
Use Json.Net to serialize your list as json string on your page.
Include jQuery and jQuery-json plugin.
Define a javascript list in a javascript function.
Something like this on your aspx page:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://jquery-json.googlecode.com/files/jquery.json-2.2.js"></script>
<script type="text/javascript">
function foo() {
// This is where we use the Json.Net library
var rawJsonString = '<%= Newtonsoft.Json.JsonConvert.SerializeObject(Model.NewList) %>';
// This is where we use the jQuery and jQuery-json plugin
var list = $.evalJSON(rawJsonString);
// Do stuff with your list here
}
</script>
THanks for the ideas. I eventually dug a little deeper with your suggestions and I used a for loop on the list I passed then add my data to the row based on the loop...
success: function(data) {
var loopList = data.message.NewList;
for (var i = 0; i < loopList.length; i++) {
addRecentData(loopList[i]);
}
},
});
function addRecentData(data) {
....
}
THanks for the nudge!

jQuery "Microsoft JScript runtime error: Object expected"

I have the below code that does not seem to work at all :( I keep getting:
Microsoft JScript runtime error: Object expected
The error seems to occur when the timeout is done. So if I raise the timeout with 10 seconds the error holds for another 10 seconds.
I want to be able to update the number of friends online async. The number is shown with the following html:
(?)</strong>
The friends part is set at the first run, but when the timeout calls back it does not fire again. Also, I cannot see on which line the error occurs because if I want to break on the error it just shows "no source code" etc.
The code below is the code I'm using. Thanks!
<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.3.2.js" type="text/javascript"></script>
<script src='/Scripts/MicrosoftAjax.js' type="text/javascript"></script>
<script src='/Scripts/MicrosoftMvcAjax.js' type="text/javascript"></script>
<script src='/Scripts/jquery.autocomplete.js' type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
UpdateFriendsOnline();
function UpdateFriendsOnline() {
window.setTimeout("UpdateFriendsOnline()", 1000);
$.get("/Account/GetFriendsOnline", function(data) {
$("#friendsOnline").html("(" + data + ")");
});
}
});
</script>
Change your setTimeout() like this:
window.setTimeout(UpdateFriendsOnline, 1000);
Currently your function isn't available outside the document.ready, so it's not accessible as a global function, which passing it as a string is trying to access it as. As a general rule, never ever pass setTimeout() a string if you can avoid it...it can cause problems like this case, and I can't think of an example (that if avoidable) is made better by it being a string.
Also, I suggest firing it when you get the response back, otherwise you'll start queuing up overlapping ajax requests, you can do that by adjusting your function to this:
function UpdateFriendsOnline() {
$.get("/Account/GetFriendsOnline", function(data) {
$("#friendsOnline").html("(" + data + ")");
window.setTimeout(UpdateFriendsOnline, 1000);
});
}
Try this:
window.setTimeout(UpdateFriendsOnline, 1000);
The version you had would have worked if the function was defined in the global namespace.
This way, you're passing in a local reference to the function, which will get called every second.
EDIT:
If you need to cancel the previous request before the new one starts, you can do something like this:
<script type="text/javascript">
$(document).ready(function() {
var request; // Stores XMLHTTPRequest object
UpdateFriendsOnline();
function UpdateFriendsOnline() {
if(request) request.abort(); // Abort current request if there is one
window.setTimeout(UpdateFriendsOnline, 1000);
// Store new XMLHTTPRequest object
request = $.get("/Account/GetFriendsOnline", function(data) {
request = null; // Clear request object upon success
$("#friendsOnline").html("(" + data + ")");
});
}
});
</script>

Categories