passing json as parameter in javascript with space in content - javascript

The following is working when the content is no space
<a onclick=fbShareDialog("{\"name\":\"aaaaaaa\"}">
but if there is a space between
<a onclick=fbShareDialog("{\"name\":\"bbbbb bbbbb\"}">
it throws Uncaught SyntaxError:unexpected token illegal
as i think all the content is in quotation , why not works?
thanks in advance

You need to make sure you escape the space and put everything within double quotes.
I can't test it out now but try something like.
Also, it may be a better idea if you didn't write this inline and wrote a function to catch the click event instead.

You're implying a quoteless-attribute, which is really bad form in HTML but unfortunately still allowed due to HTML's sordid history. The attribute is 'onclick', which actually includes fbShareDialog, but that isn't in quotes.
Try:
<a onclick='fbShareDialog({"name":"bbbbb bbbbb"})'>
Or better yet, bind your click events in a .js file for your app, not onclicks in the html.

Related

Prevent Javascript Injection in data attribute

I have a script that pulls a text from an API and sets that as a tooltip in my html.
<div class="item ttip" data-html="<?php echo $obj->titleTag;?>">...</div>
The API allows html and javascript to be entered on their side for that field.
I tried this $obj->titleTag = htmlentities(strip_tags_content($this->channel->status)));
I now had a user that entered the following (or similar, he is blocked now I cannot check it again):
\" <img src="xx" onerror=window.location.replace(https://www.youtube.com/watch?v=IAISUDbjXj0)>
which does not get caught by the above.
I could str_replace the window.location stuff, but that seems dirty.
What would be the right approach? I am reading a lot of "Whitelists" but I don't understand the concept for such a case.
//EDIT strip_tags_content comes from here: https://php.net/strip_tags#86964
Well, It's not tags you're replacing now but code within tags. You need to allow certain attributes in your code rather than stripping tags since you've only got one tag in there ;)
What you wanna do is check for any handlers being bound in the JS, a full list here, and then remove them if anything contains something like onerror or so

how to call a onclick function in <a> tag?

I want to open a new window on click of 1
$leadID = "<a href='javascript:onclick=window.open(lead_data.php?leadid=1, myWin, scrollbars=yes, width=400, height=650);'>1</a>";
It is not showing me error. Is there any other way to open new window?
Here is the fiddle
http://jsfiddle.net/ankurdhanuka/uwypv/
Try onclick function separately it can give you access to execute your function which can be used to open up a new window, for this purpose you first need to create a javascript function there you can define it and in your anchor tag you just need to call your function.
Example:
function newwin() {
myWindow=window.open('lead_data.php?leadid=1','myWin','width=400,height=650')
}
See how to call it from your anchor tag
<a onclick='newwin()'>Anchor</a>
Update
Visit this jsbin
http://jsbin.com/icUTUjI/1/edit
May be this will help you a lot to understand your problem.
Fun! There are a few things to tease out here:
$leadID seems to be a php string. Make sure it gets printed in the right place. Also be aware of all the risks involved in passing your own strings around, like cross-site scripting and SQL injection vulnerabilities. There’s really no excuse for having Internet-facing production code not running on a solid framework.
Strings in Javascript (like in PHP and usually HTML) need to be enclosed in " or ' characters. Since you’re already inside both " and ', you’ll want to escape whichever you choose. \' to escape the PHP quotes, or &apos; to escape the HTML quotes.
<a /> elements are commonly used for “hyper”links, and almost always with a href attribute to indicate their destination, like this: Google homepage.
You’re trying to double up on watching when the user clicks. Why? Because a standard click both activates the link (causing the browser to navigate to whatever URL, even that executes Javascript), and “triggers” the onclick event. Tip: Add a return false; to a Javascript event to suppress default behavior.
Within Javascript, onclick doesn’t mean anything on its own. That’s because onclick is a property, and not a variable. There has to be a reference to some object, so it knows whose onclick we’re talking about! One such object is window. You could write Activate me to reload when anything is clicked.
Within HTML, onclick can mean something on its own, as long as its part of an HTML tag: <a href="#" onclick="location.reload(); return false;">. I bet you had this in mind.
Big difference between those two kinds of = assignments. The Javascript = expects something that hasn’t been run yet. You can wrap things in a function block to signal code that should be run later, if you want to specify some arguments now (like I didn’t above with reload): <a href="javascript:window.onclick = function () { window.open( ... ) };"> ....
Did you know you don’t even need to use Javascript to signal the browser to open a link in a new window? There’s a special target attribute for that: Google homepage.
Hope those are useful.
You should read up on the onclick html attribute and the window.open() documentation. Below is what you want.
<a href='#' onclick='window.open("http://www.google.com", "myWin", "scrollbars=yes,width=400,height=650"); return false;'>1</a>
JSFiddle: http://jsfiddle.net/TBcVN/
Use the onclick as an attribute of your a, not part of the href
<a onclick='window.open("lead_data.php?leadid=1", myWin, scrollbars=yes, width=400, height=650);'>1</a>
Fiddle: http://jsfiddle.net/Wt5La/

Adding script as string into textarea value

The question is pretty self explanatory. What I want to do is changing the value of a textarea with jQuery. What I do is:
$( '#embedcode' ).val( "<script id='embed_1' src='/javascripts/test.js' type='text/javascript'></script>" );
What is the right way to do that. I keep getting an error :
Uncaught SyntaxError: Unexpected identifier
How to make the that I want to add as a string not a script.
Here you go:
Make your String like this :
$('#embedcode').val("<script id='embed_1' src='\/javascripts\/test.js' type='text\/javascript'><\/script>");
Check out this JsFiddle i made for you:
http://jsfiddle.net/KB9Qn/14/
You need to escape the "<" and ">".
$('#embedcode').val("\<script id='embed_1' src='/javascripts/test.js' type='text/javascript'\>\</script\>");
Demo
Your code seems to work perfectly. Here's the live demo: Click here
You need to check the line number where you are getting that error.
edit: I just had the thought. If your html markup has an error (maybe an unclosed textarea) the script can be evaluated as a script tag rather than text. Check for that. Here is a live example of an html error that will cause your problem. Click here.
Update: I believe I know exactly what the real issue is. The other posts are recommending that you escape the '<' and '>', but that should only be necessary if this javascript you are using is actually in an html file (or html generated by the server) rather than in a js file where it belongs. In the js file, it will naturally be a string as you have written it, but the html file sees it as markup even though it isn't intended to be. This is an example of why you should follow the best practices and keep javascript in a js file.
escape the < and > in the string with \

Iavascript \" \' I'm confused

I'm busy on little JavaScript item, but I got confused by the next rule:
<img src="images/icons/collapse.gif"><br/>'
It doesn't take the onclick remove map action. I don't know what I have to put between the () to make I can put text there. Does somebody have the solution?
Try just :
onclick="removeMap('test')"
if test is a variable:
onclick="removeMap(test)"
The \" is to scape the closing double quote of the onclick event. In this case I don't see any use in your calling. When used event functions in the html tags just like your onclick event, as html uses double quotes for the attributes you need to use the single quotes in your inline javascript functions.
By the way, have you checked about JQuery JavaScript Library. As you are starting coding javascript it's good to know your options.
Or just stop writing javascript inside of your HTML tags, just call functions and put your code in your functions... far much readeable !
How about:
<img src="images/icons/collapse.gif"><br/>'
You should use an editor that properly highlights strings (and what is going on should be obvious)
Escaped quotes don't have any special meaning in HTML. Instead, the browser will see your line as:
<a href="#"
onclick="removeMap('+ \"
test\
" +')"
style="float:right; margin-right: 30px;"
>
Where the onclick would be broken Javascript, and there would be two attributes in the tag (test\ and " +')") that it doesn't recognize and doesn't know what to do with.

Regex replace string but not inside html tag

I want to replace a string in HTML page using JavaScript but ignore it, if it is in an HTML tag, for example:
visit google search engine
you can search on google tatatata...
I want to replace google by <b>google</b>, but not here:
visit google search engine
you can search on <b>google</b> tatatata...
I tried with this one:
regex = new RegExp(">([^<]*)?(google)([^>]*)?<", 'i');
el.innerHTML = el.innerHTML.replace(regex,'>$1<b>$2</b>$3<');
but the problem: I got <b>google</b> inside the <a> tag:
visit <b>google</b> search engine
you can search on <b>google</b> tatatata...
How can fix this?
You'd be better using an html parser for this, rather than regex. I'm not sure it can be done 100% reliably.
You may or may not be able to do with with a regexp. It depends on how precisely you can define the conditions. Saying you want the string replaced except if it's in an HTML tag is not narrow enough, since everything on the page is presumably within some HTML tag (BODY if nothing else).
It would probably work better to traverse the DOM tree for this instead of trying to use a regexp on the HTML.
Parsing HTML with a regular expression is not going to be easy for anything other than trivial cases, since HTML isn't regular.
For more details see this Stackoverflow question (and answers).
I think you're all missing the question here...
When he says inside the tag, he means inside the opening tag, as in the <a href="google.com"> tag...This is something quite different than text, say, inside a <p> </p> tag pair or <body> </body>. While I don't have the answer yet, I'm struggling with this same problem and I know it has to be solvable using regex. Once I figure it out, i'll come back and post.
WORKAROUND
If You can't use a html parser or are quite confident about Your html structure try this:
do the "bad" changing
repeat replace (<[^>]*)(<[^>]+>) to $1 a few times (as much as You need)
It's a simple workaround, but works for me.
Cons?
Well... You have to do the replace twice for the case ... ...> as it removes only first unwanted tag from every tag on the page
[edit:]
SOLUTION
Why not use jQuery, put the html code into the page and do something like this:
$(containerOrSth).find('a').each(function(){
if($(this).children().length==0){
$(this).text($(this).text().replace('google','evil'));
}else{
//here You have to care about children tags, but You have to know where to expect them - before or after text. comment for more help
}
});
I'm using
regex = new RegExp("(?=[^>]*<)google", 'i');
you can't really do that, your "google" is always in some tag, either replace all or none
Well, since everything is part of a tag, your request makes no real sense. If it's just the <a /> tag, you might just check for that part. Mainly by making sure you don't have a tailing </a> tag before a fresh <a>
You can do that using REGEX, but filtering blocks like STYLE, SCRIPT and CDATA will need more work, and not implemented in the following solution.
Most of the answers state that 'your data is always in some tags' but they are missing the point, the data is always 'between' some tags, and you want to filter where it is 'in' a tag.
Note that tag characters in inline scripts will likely break this, so if they exist, they should be processed seperately with this method. Take a look at here :
complex html string.replace function
I can give you a hacky solution…
Pick a non printable character that’s not in your string…. Dup your buffer… now overwrite the tags in your dup buffer using the non printable character… perform regex to find position and length of match on dup buffer … Now you know where to perform replace in original buffer

Categories

Resources