How to document.write to parent element when external javascript called - javascript

Hello my question is how to write inside script called parent element with document.write when parent element is unknown
You may consider this as advertising script
For example:
<div>
<script src="http://www.pokemonpets.com/scripts/ads_simple.js"></script>
</div>
My script code below but not working right now
document.write('<a title="Bedava Pokemon Online Oyunu" target="_blank" href="http://www.pokemonpets.com/Register"><img src="http://orig04.deviantart.net/58d0/f/2015/213/8/4/pokemonpets_by_monstermmorpg-d93plr1.png" /></a>');
So somehow i have to make it work without knowing parent element or without knowing whether page has JQuery or not.
How does advertising companies handle this?

You don't want to use document.write, you want to find your script tag and replace it with your new content. You can do that by looking for a script tag with your URL, then having it's parent replace it.
scripts = document.getElementsByTagName("script");
for(var i in scripts){
if(scripts[i].src.indexOf('//www.pokemonpets.com/scripts/ads_simple.js') !== -1){
var wrapper = document.createElement('div');
wrapper.innerHTML = '<a title="Bedava Pokemon Online Oyunu" target="_blank" href="http://www.pokemonpets.com/Register"><img src="http://orig04.deviantart.net/58d0/f/2015/213/8/4/pokemonpets_by_monstermmorpg-d93plr1.png" /></a>';
scripts[i].parentElement.replaceChild(wrapper,scripts[i]);
}
}
This is totally untested, not even for syntax, so you might need to fiddle with it a bit.

Related

How to link two html pages

So i'm working on a chat application and i want to add smileys. So i used two html pages. the first one contain the text area when we wright the messages and an iframe that references the second html page.
<div class="col-12">
<textarea class="col-12 row-12 var_MessageInput" id="textmsg" placeholder="Write a reply..."></textarea>
</div>
in the second html page i have smiley images
<img src="../../../images/sad_smile.gif" onclick="insertSmiley('sad');"/>
<img src="../../../images/angel_smile.gif" onclick="insertSmiley('angel');"/>
<img src="../../../images/happy_smile.gif" onclick="insetSmiley('happy');" />
So i want that when i click at a smiley image that a text got inserted in my text area so i used the following script
function insertSmiley(smiley) {
var currentText = document.getElementById("textmsg");
var smileyWithPadding = " " + smiley + " ";
currentText.value += smileyWithPadding;
currentText.focus();
}
But it doens't work :( i thought the problem might be in document.getElementById since it's another html page but i have no idea how to solve it.
Thanks a lot
Have you included the <script src="Scripts_Chatapp/emoticone.js"></script> in iframe too? If yes, remove the script reference from iFrame.
Move the script reference <script src="Scripts_Chatapp/emoticone.js"></script> at top of page with other script tags.
Change the onclick="insertSmiley('sad');" TO onclick="parent.insertSmiley('sad');".
This will call the parent function and make changes on that page, since element exists on parent.
You have one typo in onclick="insetSmiley('happy');" it should be onclick="insertSmiley('happy');". I checked it and it works for me.
In your JS code, use:
window.location = "second_HTML_Page.html" ;
The problem is that when the function is triggered within the iFrame, the scopes become complicated.
A solution would be to make the function global by defining it at the window level. And then when the function is to be triggered inside the iFrame, it can call the function of the iFrame's parent (the main window).
Example Fiddle: http://jsfiddle.net/e37rrtb1/2/

the reason why Conflict between plugin and javascript function occured

Few days ago I had to write code quickly and added the bad code below.
<td class="note_box_con" onclick="getElementsByTagName('a')[0].click();">
After then, when I tried to use Text editor plugin written by Javascript, I found
Text editor plugin and the function of DOM collide into each other
Now I know what was the problem and solve it. But I cannot understand what kind of risk getElementsByTagName('a')[0].click(); has.
In my incomplete view, that code is just addEventlistener function().....
what kind of risk onclick="getElementsByTagName('a')[0].click();" has?
In my understanding, its a bad practice to do it this way. I would rather suggest you to use to fetch using classname or id.
If you are using some resource that adds anchor tags to your page, this will break your logic.
Following is a simulation:
var count = 0;
function addAnchor(){
var div = document.getElementById("content");
var str = "<a href='#'>" + count++ + "</a>";
div.innerHTML = str + div.innerHTML;
}
document.getElementsByTagName("a")[0].addEventListener("click", function(){
console.log(this.innerHTML);
return false;
})
<div id="content">
Test
</div>
<button onclick="addAnchor()">Add Link</button>
<a onclick="document.getElementsByTagName('a')[0].click()"> test </a>
Also, if there is a change in DOM structure, your code will not work properly. Best use a proper selector that uniquely identifies the element.

Using regexes to modify the text of html (with javascript)

I want to modify the text in a html file using javascript in an android webview.
Essentially, I want to do what android Linkify does to text, but I don't want to do it with java code, because I feel like that might delay the webview rendering the html (if I parse the text before sending it to the webview).
So, for example a piece of html like this:
<html>
<body>
google.com <!--these two shouldn't be linked-->
akhilcherian#gmail.com <!--these two shouldn't be linked-->
<p>www.google.com</p> <!--this should be linked-->
<p>102-232-2312 2032-122-332 </p><!-- should be linked as numbers-->
</body>
</html>
Should become this:
<html>
<body>
google.com
akhilcherian#gmail.com
<p>www.google.com</p>
<p>102-232-2312 <a href="tel:2032-122-332>2032-122-332</a> </p>
</body>
</html>
I already have the regexes to convert numbers and email ids to links, and they're working well enough. What I want to ensure is that I don't link anything that's already within tags. I've removed anchor tags, so they're not an issue, but I also need to avoid linking things like this:
<div width="1000"> <!-- Don't want this '1000' to be linked (but I do want other 4 digit numbers to be)-->
So for example if my regex for links is:
var replacePattern1 = /((https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/gim
How do I make sure that it's not within < and >? (Answers using javascript would be appreciated, but if you feel like this is a stupid way of doing it, please let me know about alternatives).
If you're answering with javascript, this question can essentially be shortened to:
How do I write a regex in javascript to search for patterns which are not surrounded by '<' '>' tags
So if you use JS than mean is client side, your DOM page have free access of all objects of your page coef events.
May be in this step you dont need to use a regex just using DOM.
jquery lib can easy update DOM object.
in your step you want only tag.
So i suggest :
//using jquery
$("p").each(function(){
console.log($(this))
});
//js
var paras = document.getElementsByTagName("p");
for(p in paras){
console.log(paras[p])
}
As i tell you the deal is manipulate the DOM so example with you step dunno if exactly what you try to get :
var paras = document.getElementsByTagName("p");
var hrefs = [];
//what you want to replace in the loop of p
var json_urls = {"links":["http://", "tel:"]};
for(p in paras){
//copy of text content of your p
var text_cp = paras[p].textContent;
//delete the p[i] content
paras[p].textContent = "";
//create element dom a
hrefs[p] = document.createElement("a");
//i add attribute id with some affectation unique
hrefs[p].id = "_" + p;
//add attribute href to a with some affectation replace + content
hrefs[p].href = json_urls.links[p] + text_cp;
hrefs[p].textContent = text_cp;
paras[p].appendChild(hrefs[p]);
}

Deleting and inserting Code in a DIV via jQuery

I know this has been adressed before, but I can't seem to get it working for me.
I am trying to create a football pitch with editable players via HTML/JavaScript/jQuery.
I can produce the field the first time when loading the page without any problems. The code looks like this:
<div id="pitch" class="updateAble">
<script type="text/javascript">
appBuilder(team1, team2);
</script></div>
appBuilder() looks like this:
var appBuilder = function (team1, team2) {
team1.Display();
team2.Display(); }
It simply creates the players on the pitch for both teams. As it does. I now want to push an input-button to call a function appUpdate(), which deletes the content of #pitch and puts the appBuilder()-part in again as to renew it (if I changed or added players):
var appUpdate = function () {
var newContent = "<script type='text/javascript'>appBuilder(team1, team2);</script>";
var updateItem = $('#pitch');
updateItem.empty();
updateItem.append(newContent);}
Here is what drives me nuts: It seems to work just fine up to and including the empty()-function. So the code has to be fine.
But when I try to append newContent to the #pitch-DIV, the programm seems to completely delete everything inside <head> and <body> it recreates a clean html-file (with empty html-, head-, body-tags) and inserts my players inside <body>.
Any ideas as to why it is doing that?
Thanks in advance!
UPADTE: The solution was a rookie mistake (which is fitting, since I'm a rookie). The Team.Display()-method was trying to do a document.write() call. As I learned: If you call document.write once the document is fully loaded, it will delete your site. Thanks to jfriend for the solution! :)
If you call document.write() AFTER the document has finished loading, then it will clear the current document and create a new empty one.
What you need to do is use DOM insertion operations rather than document.write() to add/change content in the DOM once the document has already loaded.
My guess is that the .Display() method is using document.write() and you need to change the way it works to insert content into a parent node rather than write it into the current position.
Some ways to insert content:
var newNode = document.createElement("div");
node.appendChild(newNode);
node.innerHTML = "<div>My Content</div>";
Or, if you're using jQuery, you can use it's wrappers for this:
obj.append("<div>My Content</div>");
obj.html("<div>My Content</div>");
.html() would empty and fill the div at once. Have you tried that ?
updateItem.html(newContent);
I proposed a JQuery replacement for your code that does what you want, ion the style of your own typing.
Note that I kept the .html() call to mimic your "empty()" function, but it is not necessary. Simply put he code in the append, straight into the html() et get rid of the extra unnecessary remaing bit of code.
My code replacement, as a 100% functioning .html file. Hope it helps, cheers.
<html>
<header>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
var appBuilder = function (team1, team2) {
//team1.Display();
//team2.Display();
}
var team1, team2;
</script>
</header>
<body>
<div id="pitch" class="updateAble">
<script type="text/javascript">
appBuilder(team1, team2); // Original code to be updated
</script>
</div>
<script>
var appUpdate = function () {
$("#pitch").html("<!-- Old javscript code has been flushed -->").append($("<script />", {
html: "appBuilder(team1, team2); // brand new, replaced code"
}));
}
appUpdate();
</script>
</body>
</html>

How can I strip down JavaScript code while building HTML?

I am trying to parse some HTML to find images within it.
For example, I created a dynamic div and parsed the tags like this:
var tmpDiv = document.createElement("DIV");
tmpDiv.innerHTML = html;
The HTML should be script-less however there are exceptions, one code segment had the following code under an image tag:
<img src=\"path" onload=\"NcodeImageResizer.createOn(this);\" />
By creating a temp div the "onload" function invoked itself and it created a JavaScript error.
Is there anyway to tell the browser to ignore JavaScript code while building the HTML element?
Edit:
I forgot to mention that later on I'd like to display this HTML inside a div in my document so I'm looking for a way to ignore script and not use string manipulations.
Thanks!
One way of doing this is to loop through the children of the div and remove the event handlers you wish.
Consider the following:
We have a variable containing some HTML which in turn has an onload event handler attached inline:
var html = "<img src=\"http://www.puppiesden.com/pics/1/doberman-puppy5.jpg\"
alt=\"\" onload=\"alert('hello')\" />"
One we create a container to put this HTML into, we can loop through the children and remove the relevant event handlers:
var newDiv = document.createElement("div");
$(newDiv).html(html);
$(newDiv).children().each(function(){this.onload = null});
Here's a working example: http://jsfiddle.net/XWrP3/
UPDATE
The OP is asking about removing other events at the same time. As far as I know there's no way to remove all events in an automatic way however you can simply set each one to null as required:
$(newDiv).children().each(function(){
this.onload = null;
this.onchange = null;
this.onclick = null;
});
You can do it really easily with jquery like this:
EDIT:
html
<div id="content" style="display:none">
<!-- dynamic -->
</div>
js
$("#content").append(
$(html_string).find('img').each(function(){
$(this).removeAttr("onload");
console.log($(this).attr("src"));
})
);

Categories

Resources