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
Related
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*/");
I'm trying to invoke javascript from C# in my project, I want to call a javascript function that I've defined with parameters but I'm stuck on how to do it.
MainPage.xaml has this my:CordovaView that wraps my phonegap project, but I'm a little lost on how to "inject" and run javascript into it.
Has anyone done this? I'm trying to do push messages
I haven't done this with cordova per se, but in general you just need to remember where the code is executing. The C# code is executing on the server, and the javascript is executing on the client, so, you want your C# to emit a value that can be consumed by the client.
The following javascript snippet is based on Razor engine syntax, hopefully it's enough to get you started.
function alertVar(someVal) {
alert("JS, someVal = " + someVal);
}
$(document).ready(function() {
// in this case the server interpolates #Model and returns HTML with the value replaced
// wrap it in quotes so the js engine treats that value as a string
// this method will then fire when the document loads
alertVar("#Model.ServerValueForClient");
});
This is the html that that the server would send to the client after interpolation (assuming that somewhere on the server you set the value #Model.ServerValueForClient = "set by the server";)
$(document).ready(function() {
// in this case the server interpolates #Model and returns HTML with the value replaced
// wrap it in quotes so the js engine treats that value as a string
// this method will then fire when the document loads
alertVar("set by the server");
});
HTH
I've seen a few posts about this but stills couldn't understand why this is not working
$.get('#Url.Action("Edit","Contacts")', {id: parseInt($(this).attr('id')) } , function (result) {
obviously this does
$.get("/Contacts/Edit/" + parseInt($(this).attr('id')), function (result) {
I've tried with replacements and still getting the proper id but the #Url.Actions appears as a string itself generating weird routes as this one for the former code, seems to me that the url.action is not executed, right?
localhost:53720/#Url.Action(Edit,%20Contacts)?id=23918
Edition: Actually the route generated for that code is
localhost:53720/Url.Action(%22Edit%22,%20%22Contacts%22)?id=23918
the other is for another try I've made
Anyone can tell me why?
Thanks
To have access to HtmlHelpers inside javascript, the javascript code must be inside a View page, and not inside a javascript file
<script>
var url = '#Url.Action("Edit","Contacts")';
console.log(url);
</script>
Looks like #Url.Action is not getting called and the URL is not being returned.
var url = '#Url.Action("Edit","Contacts")';
$.get(url, {id: parseInt($(this).attr('id')) } , function (result)
If JS complains about the above, you can try specifying #: beforehand to let razor take control.
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
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.