Javascript: document innerHTML replace breaks forms - javascript

I'm currently trying to replace a piece of plain text in a page that also contains a form. I am aware that upon replacing code containing a form, the form elements get recreated. This can break forms (and it does on the webpage I'm manipulating).
Usually, I go about this by using the "getElementsByTagName" function, to make sure that I don't need to replace the code containing the form and this has always been possible so far. However at this point, I have arrived at a page where the smallest tagname is a div that contains the text I need to replace and a form. This div is further subdivided in tables so initially I thought "let's get elements by table", but exactly the piece that I need to replace is not subdivided in a table.
So I used this code to replace:
document.documentElement.innerHTML = document.documentElement.innerHTML.replace(RegEx, replaceString);
Of course, this breaks the form on the page, which is not wanted behavior.
Does anyone have any idea how to go about this without breaking the form? Is it possible to somehow get a reference to the part of the div that does not contain a table? Is it possible to alter just part of the code? Right now I take an instance of the code, replace the matches in the instance, and then overwrite the original code with the altered instance. I once remember trying document.documentElement.innerHTML.replace(RegEx, replaceString); on another page but this only returned an instance of altered code, it did not alter the original code.
This is part of the page:
<div class="BoxContent" style="background-image:url(http://static.tibia.com/images/global/content/scroll.gif);">
<TABLE></TABLE>
<BR>
Some text here.
<BR>
And some more.
<table></table>
<table></table>
</div>
I need to do some changes in the text between the tables.
I have looked around on SO and found similar question about adding things to a form with innerHTML, but this did not help my cause. So, all help is appreciated here!
Kenneth

Here - plain JS
DEMO
window.onload=function() {
var nodes = document.getElementsByClassName("BoxContent")[0].childNodes;
for (var i=0,n=nodes.length;i<n;i++) {
if (nodes[i].nodeType==3) {
// console.log(nodes[i].textContent)
nodes[i].textContent=nodes[i].textContent.replace(/some/gi,"Lots");
}
}
}

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 avoid fetching a part of html page which is being called inside another page?

I am calling a .html page(say A.html, which is dynamically created by another software each time a request is made) inside another webpage (say B.html). I am doing this by using the .load() function. Everything works fine but the problem is I donot want the so many "br" tags (empty tags) present at the end of A.html into B.html. Is there any way to avoid fetching those "br" tags into B.html? Any suggestion would be of great help. Thank you in advance.
You can't avoid loading part of a file when you are just accessing it.
The best option would be to simply remove the extra <br> tags from the document to begin with. There is probably a better way to accomplish whatever they are attempting to accomplish.
With some server-side scripting, it could be possible to strip them automatically when you load it, but would probably be pretty bothersome to do.
Instead, if you can't remove the <br> elements for some reason, what might be easier, if you are just dealing with a handful of <br> tags would be to simply strip them out.
Since you mention using the load() function, I'm guessing you are using jQuery.
If that's the case, something like this would cleanly strip out any extra <br> tags from the end of the document.
Here is a JSfiddle which will do it: http://jsfiddle.net/dMJ2F/
var html = "<p>A</p><br><p>B</p><br><p>C</p><br><br /><br/>";
var $html = $('<div>').append(html);
var $br;
while (($br = $html.find('br:last-child')).length > 0) {
$br.remove();
}
$('p').text($html.html());
Basically, throw the loaded stuff in to a div (in memory), then loop through and remove each <br> at the end until there aren't any. You could use regex to do this as well, but it runs a few risks that this jQuery method doesn't.
You shout delete the br-tags in your A.html.
Substitute them by changing the class .sequence with marging-top:30px
And have an other value in your B.html-file.
You also can run this:
$('br', '.sequence').remove();​
in the load-function. It will strip all br-tags.
You can't avoid fetching a part of your page, but you CAN fetch only a part of it.
According to the jQuery docs, you can call load like this:
$("#result").load("urlorpage #form-id");
That way, you only load the form html inside the result element.

Replacing to HTML Character Entities and reverting back

When replacing things in my chat room it comes up in the box as the 'HTML Character Entities'. However, I want it to revert back and actually show the character typed in when it is then shown in the chat room. So I am using the following code to stop any html from being entered and damaging the chat room by replacing certain html character with there entities (I want to get one or two working before I look at the others I know there are many more.) ....
Javascript
var str1 = this.value.replace(/>/g, '<');
if (str1!=this.value) this.value=str1;
var str2 = this.value.replace(/</g, '>');
if (str2!=this.value) this.value=str2;
and then the following code then displays the text after it has been entered into the database etc. and on updating the chat box it uses the following to add in the the updated messages ...
Returned from php and then displayed through the following javascript
$('#chatroomarea').append($("<p>"+ data.text[i] +"</p>"));
I have messed around with this a few times changing it to val and using
.html(.append($("<p>"+ data.text[i] +"</p>")));
Etc. But I have had no luck. I'm not quite sure how to do this I just need the HTML Character Entities to actually show up back in there true Character instead of displaying something such as... '&#62'
This might be something I need to actually put within the replacing code where it will include code of it's own on replacing such as (this is just an example I'm not exactly sure on how I would write it) ....
var str1 = this.value.replace(/>/g, '.html(<)');
Any help on this would be much appreciated, Thank you.
$('#chatroomarea').append($("<xmp>"+ data.text[i] +"</xmp>"));
HTML xmp tag
The use is deprecated, but supported in most browsers.
Another option will be to use a styled textarea , To my knowledge these two are the tags that doesn't bother rendering html tags as it is.

Is it possible in JavaScript to get html page code and replace TextBoxes with it's values?

I kind of need to create html page copy by clicking on button in this page, but where all <input type = 'text'... replaced with it's values.
I think, I can handle the second part, but how first to get html code?
Are this ever possible?
I need this for generating html reports.
Page is shown in internal browser of my prog. The basic idea, the student see the page with inputs, then when he fill all, he press button inside HTML page, some JS handler work and send to my prog same page, but without inputs for later review for teacher.
If you want to get the html for the body of the document, use this:
document.body.innerHTML
You can then modify it as needed and change it:
document.body.innerHTML = ... modified html ...
There are better ways to achieve the result though, like manipulating the DOM with jQuery.
You can use document DOM element and serialize it:
(new XMLSerializer()).serializeToString(document);
for cross-browser compatibility see this post
If you have a <form> you can post to the same page adding ?post=1 to the action.
Then in the php
if ($_GET["post"]==1) {
//same table or div structure getting the values submitted by the form
}
Do you know how to do it? was this you needed?

Removing appended html using jQuery?

Using jquery, I currently append html to a div on a click event. The following code allows me to fade in only the appended portion of the div:
var html = "..";
$('<div></div>').appendTo("#id").hide().append(html).fadeIn('slow');
This portion works perfectly. But how can I later remove (fade out) only the appended portion? I tried hacking this by storing the html prior to the appending, and then simply hiding everything and showing the stored html. But this does not work well when the same procedure is reused for several divs on the same page (and this seems like poor implementation). Is there a good way to do this?
Just to give an idea of why I need this: Think of a blog type page where for every article on the page there are several comments with only x amount showing by default: the click event fetches the remaining comments and displays them, and then toggling the button again removes the appended comments and sends it back to the original state.
empty() is always an option
jQuery('#main').empty();
Give a look at the empty() function.
It might better solve the problem. Here's the link http://api.jquery.com/empty/
I'd just set and clear the html with '.html()' ...
-- edit
to be more clear, have an area layed out specifically for the addition of these comments:
<div id='commentarea1'></div>
etc.
Try:
var html = "..";
$('<div></div>').appendTo("#id").hide().append(html).fadeIn('slow').addClass('appended');
then later
$('#id .appended').fadeOut('slow'); // or whatever you want to do.
It is not that clear from the question but say you show 5 comments by default and then show x more comments. To get back to the original 5 comment default state you can remove all comments with an index greater than 4 (zero based).
The following assumes each comment goes inside its own div that has a class comment.
$('#id>div.comment:gt(4)').remove();

Categories

Resources