whay backaward slash in the parameter element of the javascript object? - javascript

I was inspecting this site in firebug. Inside the third <script/> tag in the head section of the page , I found an object variable declared in the following way ( truncated here however by me) :
var EM={
"ajaxurl":"http:\/\/ipsos.com.au\/wp-admin\/admin-ajax.php",
"bookingajaxurl":"http:\/\/ipsos.com.au\/wp-admin\/admin-ajax.php",
"locationajaxurl":"http:\/\/ipsos.com.au\/wp-admin\/admin-ajax.php?action=locations_search",
"firstDay":"1","locale":"en"};
The utility of the variable is unknown to me. What struck me is the 3 urls presented there. Why are the backward slashes present there? Couldn't it be something like :
"ajaxurl" : "http://ipsos.com.au/wp-admin/admin-ajax.php"
?

In a script element there are various character sequences (depending on the version of HTML) that will terminate the element. </script> will always do this.
<\/script> will not.
Escaping / characters will not change the meaning of the JS, but will prevent any such HTML from ending the script.

The \/\/ is to avoid the below scenario:
when the url looks something similar to "ajaxurl" : "http://google.com/search?q=</script>"
Try copy paste the url in browsers address bar. This is handled correctly. Otherwise, You might end up getting script errors and page might not work as you've expected.
imagine DOM manipulators replacing the value as it is in the src attribute of the script tag and then the javascript engine reporting multiple errors because that particular script referenced might not get loaded due to incorrectly defined src value
Hope this helps.
Life would be hectic without these lil things

It is used to escape the characters..
The backslash () can be used to insert apostrophes, new lines, quotes, and other special characters into a string.
var str = " Hello "World" !! ";
alert(str)
This won't work..
You have to escape them first
var str = " Hello \"World\" !! ";
alert(str) ; \\ This works
In terms of Javascript / and <\/ are identical inside a string. As far as HTML is concerned </ starts an end tag but <\/ does not.

Related

Javascript How to escape \u in string literal

Strange thing...
I have a string literal that is passed to my source code as a constant token (I cannot prehandle or escape it beforehand).
Example
var username = "MYDOMAIN\tom";
username = username.replace('MYDOMAIN','');
The string somewhere contains a backslash followed by a character.
It's too late to escape the backslash at this point, so I have to escape these special characters individually like
username = username.replace(/\t/ig, 't');
However, that does not work in the following scenario:
var username = "MYDOMAIN\ulrike";
\u seems to introduce a unicode character sequence. \uLRIK cannot be interpreted as a unicode sign so the Javascript engine stops interpreting at this point and my replace(/\u/ig,'u') comes too late.
Has anybody a suggestion or workaround on how to escape such a non-unicode character sequence contained in a given string literal? It seems a similar issue with \b like in "MYDOMAIN\bernd".
I have a string literal that is passed to my source code
Assuming you don't have any < or >, move this to inside an HTML control (instead of inside your script block) or element and use Javacript to read the value. Something like
<div id="myServerData">
MYDOMAIN\tom
</div>
and you retrieve it so
alert(document.getElementById("myServerData").innerText);
IMPORTANT : injecting unescaped content, where the user can control the content (say this is data entered in some other page) is a security risk. This goes for whether you are injecting it in script or HTML
Writing var username = "MYDOMAIN\ulrike"; will throw a syntax error. I think you have this string coming from somewhere.
I would suggest creating some html element and setting it's innerHTML to the received value, and then picking it up.
Have something like:
<div id="demo"></div>
Then do document.getElementById("demo").innerHTML = username;
Then read the value from there as document.getElementById("demo").innerHTML;
This should work I guess.
Important: Please make sure this does not expose the webpage to script injections. If it does, this method is bad, don't use it.

Javascript with Special Chartecter

I have a html page in which I need to pass a String variable to javascript function. This works until String does not have a special charecter.
<html>
<head>
<script>
function test(v){
alert(v);
}
</script>
</head>
<body>
<input type="button" value="Test Button" onClick="test('BlahBlah')"/>
</body>
</html>
As soon as I change onClick like below, it stops working.
onClick="test('Blah'Blah')"
Any solution for this problem. Please take a note parameter which is being passed to JavaScript function is dynamic.Source of Parameter is backend and I cannot change that peice of code. Second thing even if put escape it still does not work. My problem is I have to retian the special charecter for some processing at backend
There are two layers to this:
The content of onClick attributes, like all attributes, is HTML text. That means that any character that's special in HTML (like <) must be replaced with an HTML entity (e.g., <). Additionally, if you use double quotes around the attribute value, any double quotes within the value must be replaced with entities ("); if you used single quotes around the attribute, you'd need to replace ' with &apos;.
Your attribute contains a JavaScript string literal. That means that any characters that are special inside JavaScript string literals must be escaped according to the JavaScript rules. Since you've used single quotes to delimit the JavaScript string, for instance, you have to escape any single quotes in the string with a backslash.
I'm assuming that HTML is generated server-side. If so, the work above must be done server-side, when building the HTML of the page. You haven't said what server-side tech you're using, so it's hard to point you at solutions that your server-side tech/environment might provide.
In the simple case of your
onClick="test('Blah'Blah')"
...you just need to add the backslash within the JavaScript string
onClick="test('Blah\'Blah')"
...but that's just that one specific case.
The dramatically simpler option is to not put JavaScript code in attribute values. Instead, use modern techniques (addEventListener, attachEvent) to hook up JavaScript code.
But if you must use an onClick attribute, avoid having text in it (or deal with the complexities above); have it call a function defined in a script element that then has the text, as you then have only the one layer (#2 above) to deal with.
Source of Parameter is backend and I cannot change that peice of code.
That backend is broken and needs fixing.
If:
the backend is only producing invalid JavaScript code (not invalid HTML)
and the code consists of a single function call
and the code is always a single function call
and the function call always has a single string literal argument
and that argument is always delimited with single quotes
and the single quotes within the string are never correctly escaped
...we might be able to salvage it client-side. But my guess is that the backend will also produce invalid HTML, for instance when the text has a " in it. (We can't do anything about that, because the attribute value will be chopped off at that point.)
But let's keep a good thought: Given the ridiculous list of caveats above, this might do it:
var elm = document.getElementById("the-div");
var code = elm.getAttribute("onclick");
var m = code.match(/^([^(]+)\('(.*)'\)$/);
if (m) {
code = m[1] + "('" + m[2].replace(/'/g, "\\'") + "')";
}
elm.setAttribute("onclick", code);
Live Example:
function foo(str) {
alert(str);
}
var elm = document.getElementById("the-div");
var code = elm.getAttribute("onclick");
var m = code.match(/^([^(]+)\('(.*)'\)$/);
if (m) {
code = m[1] + "('" + m[2].replace(/'/g, "\\'") + "')";
}
elm.setAttribute("onclick", code);
<div id="the-div" onclick="foo('blah'blah')">Click me</div>
Well this is an very common problem you wanted to add single quotes inside single quotes to do this you have to escape that Sigle quotes to do that you have to put an forward slash.
onClick="test('Blah\'Blah')"

JavaScript and XML and HTML tags

Using JavaScript to create an xml file (for later saving in PDF). When user enters some HTML characters, like < and >, these cause problems because the program thinks they are Beginning and End HTML tags. We’ve tried the Replace function but have not found the correct Syntax yet. Any ideas?
You might try :
'<foo><bar></foo></bar>'.replace(/>/g, '<').replace(/</g, '>')
The gat the end of the regex is really important b/c otherwise it will only replace the first occurence.

Wordpress & Javascript: String variable having html tags being read by browser with newline character

I have gone crazy trying to resolve this issue.
In my javascript code I have am defining a string variable in which I am putting an HTML table in the form of string.. i.e.:
var tData="<table><tbody><tr><a><th>Type</th><th>Score</th><th>Percentile</th></a></tr><tr><td><a>Overall</a></td><td>2.4</td><td>50%</td></tr><tr><td><a>Best 100</a></td><td>2.3</td><td>70%</td></tr></tbody></table>";
Now this variable assignment through the string is being read by my browser (both chrome and firefox) as an HTML code with line breaks. Take a look at the image below for more clarity.
The code works fine if I remove html tags and write a simple string. So I can assure you there are no previous inverted comma errors (i checked them multiple times) and no bogus characters.
I have spent too many hours on this issue. Please please help me on this.
EDIT
Added Wordpress in title and Tags as this is a wordpress issue.
Since your document is XHTML, you have to enclose your code into a CDATA section:
<script>
<![CDATA[
// code here
]]>
</script>
This prevents the browser from interpreting <...> sequences in the content as tags.
If you want multiline strings in JavaScript, you have to unescape the newline, ie
var str = "abc\
de";
Ok. Eureka!!!
I found a get around. I broke the following string :
var tData="<table><tbody><tr><a><th>Type</th><th>Score</th><th>Percentile</th></a></tr><tr><td><a>Overall</a></td><td>2.4</td><td>50%</td></tr><tr><td><a>Best 100</a></td><td>2.3</td><td>70%</td></tr></tbody></table>";
into
var tData = "<tab"+"le><tb"+"ody><t"+"r><a><t"+"h>Type</t"+"h><t"+"h>Score</t"+"h><t"+"h>Percentile</t"+"h></a></t"+"r><t"+"r><t"+"d><a>Overall</a></t"+"d><t"+"d>2.4</t"+"d><t"+"d>50%</t"+"d></t"+"r><t"+"r><t"+"d><a>Best 100</a></t"+"d><t"+"d>2.3</t"+"d><t"+"d>70%</t"+"d></t"+"r></tbo"+"dy></ta"+"ble>";
to fool the browser. I am still hoping for a better answer please.
Delete all invisible characters (whitespace) around that area,
then give it another try.
Try this:
var tData="<table><tbody>";
tData+="<tr><th><a>Type</a></th><th>Score</th><th>Percentile</th></tr>";
tData+="<tr><td><a>Overall</a></td><td>2.4</td><td>50%</td></tr>";
tData+="<tr><td><a>Best 100</a></td><td>2.3</td><td>70%</td></tr>";
tData+="</tbody></table>";
Possible Duplicate No visible cause for "Unexpected token ILLEGAL"

Javascript regex whitespace is being wacky

I'm trying to write a regex that searches a page for any script tags and extracts the script content, and in order to accommodate any HTML-writing style, I want my regex to include script tags with any arbitrary number of whitespace characters (e.g. <script type = blahblah> and <script type=blahblah> should both be found). My first attempt ended up with funky results, so I broke down the problem into something simpler, and decided to just test and play around with a regex like /\s*h\s*/g.
When testing it out on string, for some reason completely arbitrary amounts of whitespace around the 'h' would be a match, and other arbitrary amounts wouldn't, e.g. something like " h " would match but " h " wouldn't. Does anyone have an idea of why this occurring or the the error I'm making?
Since you're using JavaScript, why can't you just use getElementsByTagName('script')? That's how you should be doing it.
If you somehow have an HTML string, create an iframe and dump the HTML into it, then run getElementsByTagName('script') on it.
OK, to extend Kolink's answer, you don't need an iframe, or event handlers:
var temp = document.createElement('div');
temp.innerHTML = otherHtml;
var scripts = temp.getElementsByTagName('script');
... now scripts is a DOM collection of the script elements - and the script doesn't get executed ...
Why regex is not a fantastic idea for this:
As a <script> element may not contain the string </script> anywhere, writing a regex to match them would not be difficult: /<script[.\n]+?<\/script>/gi
It looks like you want to only match scripts with a specific type attribute. You could try to include that in your pattern too: /<script[^>]+type\s*=\s*(["']?)blahblah\1[.\n]*?<\/script>/gi - but that is horrible. (That's what happens when you use regular expressions on irregular strings, you need to simplify)
So instead you iterate through all the basic matched scripts, extract the starting tag: result.match(/<script[^>]*>/i)[0] and within that, search for your type attribute /type\s*=\s*((["'])blahblah\2|\bblahblah\b)/.test(startTag). Oh look - it's back to horrible - simplify!
This time via normalisation:
startTag = startTag.replace(/\s*=\s*/g, '=').replace(/=([^\s"'>]+)/g, '="$1"') - now you're in danger territory, what if the = is inside a quoted string? Can you see how it just gets more and more complicated?
You can only have this work using regex if you make robust assumptions about the HTML you'll use it on (i.e. to make it regular). Otherwise your problems will grow and grow and grow!
disclaimer: I haven't tested any of the regex used to see if they do what I say they do, they're just example attempts.

Categories

Resources