Javascript code inside var - javascript

I need to add some HTML and Javascript code inside a javascript variable to write them later in my .html page
example of what i tried to write in my Javascript page
var footer = "<footer><script>
if(isMobile.any()){
document.write('<a href="twitter:///user?screen_name=twitter">');
} else {
document.write('<a href="https://twitter.com/twitter">');
}</script></footer>";
and the way im writing it in my HTML document
<script>document.write(footer);</script>
but im getting errors inside my javascript page caused by the javascript code inside the variable
sorry i'm new in javascript and thanks in advance

Strings can't go across multiple lines without proper handling; embedded quotes need to be escaped too; this is by no means the cleanest way, but one suggestion could be:
var footer =
"<footer><script>" +
"if(isMobile.any()) {" +
"document.write('<a href=\"twitter:///user?screen_name=twitter\">');" +
"} else {" +
"document.write('<a href=\"https://twitter.com/twitter\">');" +
"}" +
"</script></footer>";
Also note that you use document.write inside script tags, when your literal script string has that tag. You need it for that piece of script, but you might consider your overall output.

You need to escape the quotes(") inside the string like \":
var footer = "<footer><script>
if(isMobile.any()){
document.write('<a href=\"twitter:///user?screen_name=twitter\">');
} else {
document.write('<a href=\"https://twitter.com/twitter\">');
}</script></footer>";

var footer = "<footer><script>
if(isMobile.any()){
document.write('<a href='twitter:///user?screen_name=twitter'>');
} else {
document.write('<a href='https://twitter.com/twitter'>');
}</script></footer>";
as another answer already pointed out, when the second double qute is encountered, it's considered as the end if the string, you've to either escape it, or use single quotes throughout the string, as above.

This is a slight modification to #Grant Thomas's answer
var footer = "<footer>\x3Cscript>\
if(isMobile.any()){\
document.write('<a href=\"twitter:///user?screen_name=twitter\">');\
} else {\
document.write('<a href=\"https://twitter.com/twitter\">');\
}\x3C/script></footer>";
You can read up about why you need to use \x3c here Link

Related

what is proper syntax for regex to get specific text from GTM attribute.response

I used Google Tag Manager to create a custom data level variable to get the content of an ajax form. The result is in the attributes.response that looks like:
response:"{\"current_url\":\"https:\\/\\/domainname.com\\/ +
"manufacturer\\/category\\/model-number\\/\",\"h" +
"tml"\":{\"cart_status_528\":\"\\n <div id=\\\"s" +
...
"<a href=\\\"https:\\/\\/domainname.com\\/manufacturer" +
"-name\\/long-store-category-name\\/model-number-x\\/\\" +
"\" class=\\\"ty-product-notification__product-name\\\"" +
">PRODUCT-NAME THAT I WANT<\\/a>\\n " +
...
" <p><\\n more escaped html content +
}"
I am trying to extract/parse the attribute.response to retrieve the PRODUCT-NAME text. I have tried the following which matches in regexr. But, GTM keeps complaining there is an error in my javascript at the double quote symbol. What am I missing? Or is there a cleaner way to retrieve the text? Thanks
function() {
var regex = (?<=product-name(.|\n)*">)(.*)(?=<\\\\\/a);
var attributesResponse = {{attributes.response}};
if(regex.test{{attributesResponse}}
var ProductAddedToCart = regex.exec(attributesResponse)[1];
return ProductAddedToCart;
}
return false;
}
First of all, please read the top answer here: RegEx match open tags except XHTML self-contained tags
Secondly, your JS has many problems. Even the SO code highlighter indicates it. See some examples of how regex is used in JS.
The proper way to solve your task, however, would be adding a dataLayer push with the proper response details neatly stored in a dataLayer object. You would normally ask your front-end developers to add a push in their response callback. It should be trivial for them to tackle. You can read more on DL here.

Built up string causing a syntax issue

I have a c# function that builds a string which in turn is used as a hyperlink to another page. However, with some strings with single quotes it is causing a javascript error as shown here:
I'm calling the javascript function in the code behind as so
linkFullMatch.NavigateUrl = "javascript:showFullMatches(" + sb.ToString() + ")";
the javascript is on the aspx function as so:
<script>
function showFullMatches(url) {
window.open(url, "_blank", "height=344,width=1100,scrollbars=yes,resizable=yes,toolbar=no,location=no,status=no,menubar=no,left=580,top=194");
}
Any help would be greatly appreciated. Any string that doesn't have a single quote in works fine and the page link opens as requested.
Rob
You need to add an additional layer of quote marks to make the sb.ToString() value an JS string. Adjust your call like:
linkFullMatch.NavigateUrl = "javascript:showFullMatches('" + sb.ToString() + "')";
Note the additional ' marks.

Escape single quotes inside script tag php

I have the following:
<?php echo '<script type="text/javascript">(function(d) {var url="http://myurl.com"; var iframe = d.createElement("iframe");(iframe.frameElement || iframe).style.cssText = "width: 0; height: 0;border: 0;"; iframe.src = "javascript:false"; d.body.appendChild(iframe);var doc = iframe.contentWindow.document; doc.open().write(\'<body onload="window.location.href=\'+url+\'">\'); doc.close();})(document); </script>'; ?>
Which creates and iframe on a page and set the onload property of body tag of the iframe to the value of url variable.
The problem I have is this that I want the value of the url to be surrounded by single quotes like:
<body onload="window.location.href='http://myurl.com'"></body> (**Noticed the single quotes around the url?**)
But instead I got:
<body onload="window.location.href=http://myurl.com"></body> (**without single quotes around the url**)
Can anybody help?
Thanks in advance
Try this:
<?php echo "<script type='text/javascript'>
(function(d){
var url='http://myurl.com';
var iframe = d.createElement('iframe');
(iframe.frameElement || iframe).style.cssText = 'width: 0; height: 0;border: 0;';
iframe.src = 'javascript:false';
d.body.appendChild(iframe);
var doc = iframe.contentWindow.document;
doc.open().write('<body onload=\"window.location.href=\''+url+'\'\">');
doc.close();
})(document);
</script>";
?>
The main error is in the way that you're scaping the single quote.
Because you're trying to get the href value you need to scape first and concatenate, is easier if you use double quote to manage the strings inside PHP. In this way the onload function can be load using \" , and for get the url value just do \' inside the main string.
Also don't worry if you split the Javascript in more lines, that will be do easier identify the errors.
I would use a HEREDOC, personally. They aren't that well known but they are very powerful way of doing strings
<?php
echo <<<CODE
<script type="text/javascript">(function(d) {var url="http://myurl.com"; var iframe = d.createElement("iframe");(iframe.frameElement || iframe).style.cssText = "width: 0; height: 0;border: 0;"; iframe.src = "javascript:false"; d.body.appendChild(iframe);var doc = iframe.contentWindow.document; doc.open().write('<body onload="window.location.href=\''+url+'\'">'); doc.close();})(document); </script>
CODE; //<-- note nothing can come before or after this no spaces or even this comment.
AS I put in the code nothing can come before/after the ending Identifier ( SCRIPT in this case) not even a single space or it wont work. Except the ; you can actually leave that out when putting it in an array, but that's a story for another day.
The Identifier can be anything but it should not appear in the text is a good general rule.
The advantage here is we are not using a quote or single quote to mark this as a string so it frees us up to use both. There is no need to escape them with this, outside of the normal use (no need for PHP's purposes)
The HEREDOC (above) works like " as far as variable interpolation ( replaces variables with their value).
The NOWDOC version works like ' where it does not replace variables. that is done like this
<?php
<<<'TAG'
SOME CONTENT
TAG;
Notice the <<<'TAG' instead of <<<TAG. The same rules apply as I mentioned above for the ending "tag". This is very very very important, which is why I made it bold and mentioned it 3 times.
UPDATE
As mentioned in the comments, if you want extra ' around the url, you will have to escape them, but this is for Javascripts purposes, not PHP. Overall it still makes the code easier to deal with.
.write('<body onload="window.location.href=\''+url+'\'">');
Because there is no way around having to escape that for Javascript, but you don't have to worry about additional escaping due to PHP. I'm pretty sure without the HEREDOC you would need to add 2 additional \ to it like this href=\\\''+url+'\\\' which is pretty ugly, Or change your double quotes to ' which I really don't like tags with single quotes (its a pet peeve of mine) <script type='text/javascript' ... it's just ugly to me.

how to embed value with an apostrophe in querystring

I have the following javascript:
tr.append("<a href='add_widget.html?id=" + data[i].id + "&pg=" + data[i].page_number + "&dest=" + data[i].dest + "&name=" + data[i].name.replace("'","\\'") + "'</a><button class='btn btn-xs btn-primary'>Edit</button> </td>");
The code in question has to do with the name field.
If I have a name like "John Doe" when I click on the hyperlink created by the above javascript, the new page's querystring has the full name.
However, if I try to pass a name like "John's stuff", the above logic creates a query string variable that looks like this:
&name=John\
How can I change the above code so that the entire string "John's stuff" is passed to the add_widget.html page?
Thanks.
replace("'","%27")
try http://meyerweb.com/eric/tools/dencoder/ it's an online URL encoder/decoder.
When you're trying to "protect" characters, you have to keep in mind what you're protecting them from. In this case, there are two interpreters you have to worry about:
You're building HTML, so you have to worry about the HTML parser;
You're building a URL, so you have to worry about how the browser and the server will parse the URL.
To deal with the first problem, you can replace the quotes with the HTML entity equivalent ('). To deal with the second, you can use encodeURIComponent().
I think you'd want to do the encodeURIComponent() call first, to avoid having the HTML entity notation get messed up. The entity notation will be gone after the HTML parser is finished with the string anyway:
function qEncode(str) {
return encodeURIComponent(str).replace(/'/g, "'");
}
To use that:
tr.append("<a href='add_widget.html?id=" +
qEncode(data[i].id) + "&pg=" +
qEncode(data[i].page_number) + "&dest=" +
qEncode(data[i].dest) + "&name=" +
qEncode(data[i].name) +
"'</a><button class='btn btn-xs btn-primary'>Edit</button> </td>"
);
Note that you could also encode double-quote characters too.
A totally different way of working around this problem would be to build the DOM content with DOM APIs. By doing that, you'd completely avoid the HTML parser, and you'd just need encodeURIComponent().
You need to think, what will be interpreting my code, so what do I need to escape for?
Your code will be interpreted by the HTML Interpreter in the browser
Your code will be interpreted as a URI
This means you need to escape/encode them in reverse order. Luckily JavaScript provides a URI encoder as encodeURIComponent, but it doesn't provide a HTML one (probably as we have DOM Methods) but it isn't too hard to implement for important characters, e.g.
function html_encode(str) {
var re_chars = /[<>'"]/g;
function replacer($0) {
return '&#' + $0.charCodeAt(0) + ';'
}
return str.replace(re_chars, replacer);
}
// example follows
html_encode('<foo bar="baz">'); // "<foo bar="baz">"
So for you,
attrib_value = html_encode(/* ... + */ encodeURIComponent(data[i].name) /* + ... */ );
For completeness,
function html_decode(str) {
var re = /&(?:#\d{1,3}|amp|quot|lt|gt|nbsp);/g, // notice extra entities
d = document.createElement('div');
function replacer($0) {
d.innerHTML = $0;
return d.textContent;
}
return str.replace(re, replacer);
}
// and an example
html_decode('<foo bar="baz">'); // "<foo bar="baz">"
Using escape(data[i].name) instead of data[i].name.replace("'","\\'"), will solve your problem.

escaping a JS reserved word (already double encapsulated)

I have a JS function which is generated by some PHP, the function call is below:
onClick=openPopup('".$row['imgname']."','".$row['adtitle']."','".$row['adviews']."')
Now this works unless the value of $row['adtitle'] contains a JS keyword. The one that brought the bug in my code to my attention was the word 'THIS'. Would there be a way to escape these values, I can't figure it out as I have already used a lot of encapsulation in this call.
Thanks in advance.
EDIT:
openPopup('efc86f7223790e91f423ef1b73278435.jpg','THIS IS A TEST ADVERT 12345678','2')
This call does not work.
openPopup('eada91a6c1197d2f2320e59f45d8ca6b.jpg','is a test','2')
however this one does work..
only thing I could figure was the THIS as when looking at the source, the text following THIS is highlighed differently.
Edit 2 : Here is my function:
function openPopup(imgname,adtitle,adviews) {
document.getElementById('popup').style.display = 'block';
document.getElementById('delimg').src = 'imgstore/' + imgname;
document.getElementById('delAdTitle').innerHTML = adtitle;
document.getElementById('delAdViews').innerHTML = adviews;
document.getElementById('confirm').onclick = function() {
location.href = '?delete=1&id=' + imgname;
}
}
Maybe it’s just a question of proper formatting:
$onclick = 'openPopup('.json_encode($row['imgname']).','.json_encode($row['adtitle']).','.json_encode($row['adviews']).')';
echo 'onClick="'.htmlspecialchars($onclick).'"';
Note that we’re abusing json_encode here to quote the JavaScript string literals. Although we shouldn’t as strictly speaking JSON strings are not a subset of JavaScript strings.

Categories

Resources