InvokeScript works but WebPage replies "invalid argumment" - javascript

my script function is already defined in current loaded document
I am using
WebBrowser.InvokeScript Method (String, Object[])
as specified in MSDN to invoke a javascript method with the same arguments specified here in href.
<a style="cursor: auto ! important;" id="13185-SL-CK-0" href="javascript:jpBook($('#13185-SL-CK-0'),'13185','SDAH','DBG','24-10-2015','SL','CK',3,false);" tabindex="1">Book Now</a>
My Code is :
webBrowser1.Document.InvokeScript("jpBook", new object[] { "$('#13185-SL-CK-0')", "'13185'","'SDAH'","'DBG'","'24-10-2015'","'SL'","'CK'","3","false" });
However this doesn't work and i get a message from WebPage in a MessageBox that the arguments supplied to it are invalid.
However as you can see i have supplied the correct arguments.I am using a WebBrowserControl and have modified registry values for app to ensure that it emulates IE11

My assumption is that you need to pass without the inner single quotes as the JavaScript function is expecting a string SDAH for example not the string 'SDAH'
I haven't used the exact same api but in my project I'm invoking the script on a WebView passing a string from a variable which is just a normal string without the single quotes, also looking the MSDN example it looks they are doing the same.
For example I'm using:
anchorId is just a simple string variable like "Test1234"
C# code:
sender.InvokeScript("gotoAnchor", new string[] { anchorId });
Javascript code
function gotoAnchor(anchor) {
var myanchor = anchor;
var target_top=jQuery('#' + myanchor).offset().top-45;
$('html, body').animate({ scrollTop: target_top }, 600);
}
If I were you I'd try first with a simple function with just one parameter to see if it works, eg pass a string and write some text on html element, and then try the number and boolean values, at the end I'd also pass the first one
$('#13185-SL-CK-0' only like this "13185-SL-CK-0"
and will modify the js function to find the element inside as it might be expecting jquery object right now as parameter
Hope my assumptions are correct and this works out for you

Related

pass String to function writing javascript

I'm trying to pass a string argument to JavaScript function.
for some reason, it can get only ints.
I put here only the syntax of the string, since I know that this is the problem because it worls with int.
Code inside sending function:
String counter = "hey";
out.println("<script>parent.update(\'' + counter + '\')</script>");
out.flush();
Eventually I'd expect following update function on my HTML page to be called with value of counter as shown above:
<script>
function update(p) { alert(p); }
</script>
as I mentioned, the javascript file does alert when I send an int, but doesn't react when I send a string.
What you are trying to do called "string interpolation" and used in other languages - you can have formatting string and get values automatically inserted to it.
The code you've used does not do that - since you pass just single string to out.println it is printed as is.
Your options
construct string with concatenation
out.println("<script>parent.update('" +
counter +
"')</script>");
use String.format as shown in String variable interpolation Java
out.println(String.Format("<script>parent.update('%s')</script>",
counter));
Note: if value you are trying to pass to JavaScript function may contain quotes (especially if coming from user's input) you'd need to escape it first.

How to pass a string as a parameter into a javascript function from a View?

I've just started to work with ASP.NET MVC projects, I have gotten past the basics, but I came across with a problem recently, I can't pass a string as a id from a View.
So far, I've been passing the id to a javascript function like this:
<script>app.init( <%: ViewContext.RouteData.Values["id"].ToString() %>)</script>
This calls the following javascript function:
var app = {};
(function (app) {
var _id;
app.init = function (id) {
_id = id;
}
app.id = function () {
return _id;
}
})(app);
I'm doing this because I need to work with the id to perform operations like submits and ajax calls in javascript (I prefer working with javascript).
So far this has worked with int values, but when I tried to pass a string it fails. For example if I try to access to this url localhost:65097/Device/Edit/D2C02 it shows the following error:
SCRIPT5009: 'D2C02' is undefined
When I check the generated html code, the call to the function looked like this:
<script>app.init(D2C02)</script>
Shouldn't the id be passed as 'D2C02' like a string, instead of just D2C02 like a variable? Because that's what I'm understading the browser thinks the id D2C02 represents. How can I make sure the id value is passed on to the javascript function as a string?
ToString() just converts something to a string - but that's a C# string, not a JS string. So the easiest solution is to add quotes assuming the value can never contain quotes, too:
<script>app.init("<%: ViewContext.RouteData.Values["id"].ToString() %>")</script>
If it may contain quotes you can either perform a simple replacement to backslash-escape them or run the string through a JSON serializer that takes care of turning it into a valid JavaScript string.
Try
app.init("<%......%>");
Otherwise you are just posting in a variable name and not string. The ToString() method in c# doesn't wrap the vale in quotes
The approach I would use is to do something like this, to make things a bit more semantic -- this is overly simplified to demonstrate:
<body>
<input id="myId" type="hidden" value="<%: ViewContext.RouteData.Values["id"].ToString() %>" />
...
<script language="text/javascript">
function getId() {
return document.getElementById("myId").value;
}
</script>
</body>

how to call javascript function from client side on anchor click

I have javascript function sample('textValue') and have to call at server side on anchor click. I tried below code
string text="xyz";
anchor.Attributes.Add("onclick","javascript:sample('"+text+"');
but the value of the text is not assigning correctly. Encoded string gets added. The result in view source looks like
javascript:sample('xyz')
But i need javascript:sample('xyz')
What server/backend language do you use? PHP? Do you use any framework (Zend, CakePHP...)?
On the JS side do something like this:
Option 1
Test
Option 2
Test
<script type="text/javascript">
document.getElementById('clicky-clack-link').onClick = function() {
sample('test');
};
</script>
Note: Also check out jQuery if you haven't.
I wonder if you could just do this:
string text="xyz";
anchor.Attributes.Add("onclick", function(){ sample(text); } );
What does it do? Well, the onclick handler takes a function with no arguments, right? That is, what to do if somebody clicks the link. If you're coding this by hand in HTML, you can use the javascript:a_statement_goes_here to describe the code to run. I expect the browser will just create a function out of that. Since you're assigning this in JavaScript, you have to do that yourself (unless you write out to the document - that might work) and assign the function. But you don't have such a function yet - you have one sample that takes an argument - hence the anonymous function closing the text argument.
This is based on the assumption, that the above is actually client-side code. I'd be very surprised, if JS didn't allow you to assign a function to an attribute. In fact, I think the problem you are running into, is JavaScript trying to be very smart and make sure assigning a string, will stay a string - that is why your ' got encoded.
Have a go, tell me how it went. Ta!

Javascript pass variable in href onclick request

I know this is really basic javascript but for some reason, I can't seem to get my link's onclick function to work when passing a parameter.
I have tried escaping the quotes, adding different types of quotes and adding the raw variable as a string.
I have it working with the below but it says that "XYZ is undefined"
function renderLink(value, meta, record)
{
var type = record.data['name']; //value is XYZ
return '';
}
function getReport(type){
alert(type);
}
return '';
You need to escape the string:
return '';
If you look at the rendered HTML, you'll see the problem: Your getReport call looks like this:
getReport(XYZ);
I'm guessing you want quotes around that, so:
return '';
...which renders:
getReport('XYZ');
Live example
Somewhat more esoteric, but when you output an onclick attribute as part of HTML source, it is of course an HTML attribute, which means you can use character entities. So you could use the " entity:
return '';
Live example
I point this out not because I recommend it (I don't), but because it's useful to remember what's really going on in an onclick attribute. This is one of the reasons I would strongly recommend using a proper event handler (e.g., via addEventListener / attachEvent, or even just assigning to the a element's onclick property once it's been instantiated) instead.
It's important to note that this way of doing it is also very sensitive to the content of record.data['name']. For instance, consider what happens if instead of XYZ it's Tom's. The output of the first option above would be
getReport('Tom's');
...which is obviously a problem. Similarly, if there's a backslash in the text, it will be treated as an escape character on the result, etc., etc. — a bit of a minefield.
If you can possibly change your renderLink so it returns an actual instantiated a element rather than a string, that's what I'd do:
function createLink(value, meta, record)
{
var type = record.data['name']; // Grab value as of when we were called
var link = document.createElement('a');
link.href = "javascript:void(0);";
link.onclick = function() { // Or even better, addEventListener / attachEvent
getReport(type);
return false;
};
return link;
}
That creates the link and a closure that accesses type without turning it into text and back again. (Don't worry if you're unfamiliar with closures, closures are not complicated.)
Live example
getReport receives XYZ as a variable not as a string, you need to put that inside quotes:
return '';

Passing Variables Javascript

I am trying to pass a variable in javascript. I create a link in the following manner and everything seems to be working.
label.innerHTML = ' link';
However when I create the link in the following way where the link would also pass an associated object I get the following error from firebug -> "missing ] after element list"
label.innerHTML = ' link';
Is this an acceptable way to pass an object to a function. The problem is that I am creating this link within a function. The function creates links like this based upon an object that is passed to it. Therefore I cannot have this "object" as a global scope.
You are building the script by mashing together strings, as such you can only work with strings and object will be automatically stringified.
Use DOM instead.
var link = document.createElement('a');
link.href = "#"; // Have a more sensible fall back for status bar readers and middle clickers
link.appendChild(document.createTextNode(' link');
link.addEventListener('click',function () { show_box(this, object); },false);
label.appendChild(link);
… but use a library that abstracts away the non-standard event models that some browsers have.
What you're trying to do is pass the contents of object to output. Since it's an object, the string representation will be something like [object Object]. The output HTML would look like:
link
which is invalid. Don't try to concatenate the object, just pass it along as another argument to the function, like this. Or, better yet, use jQuery:
<!-- somewhere in the head, or at least after the object is defined -->
<script type="text/javascript">
$(function() {
$('#thelink').click(function() { show_box(this, object); });
});
</script>
...
link
If your object is simple variable like numeric or string variable than it will be Ok but if you are passing html object it will not work because it will be something like below.
link

Categories