html page disappears after onclick("open()") event - javascript

I wrote an html as
html>
<head>
</head>
<body>
<span onclick = "open()">open</span>
<script src= "script.js"></script>
</body>
</html>
and javascript as
function open(){
var id = "10";
}
whenever I click on the open text in the browser the whole page gets wiped out . Is "open" a reserved word in javascript as with any method name it works(screen doesn't get wiped out) . Just wondering what is happening behind the scene. Any information is appreciated.

I actually came across a similar question recently - the reason this is happening is because open() is being interpreted as window.open(). When no parameters are passed into this function, it navigates to a blank window.
You might be able to circumvent this by putting your script in the head, but a better recommendation is to give your function a more meaningful name.
Side note: Not certain if the behavior is the same across browsers, but in Google Chrome, calling open() opens a new tab.
Further reading on the function here: https://developer.mozilla.org/en-US/docs/Web/API/Window/open

as a general rule you will have a lot of conflicts if you program that way - you need to be more modular - use objects/json for namespacing
<html>
<body>
<span onclick = "mylibrary.open()">open</span>
<script src= "script.js"></script>
</body>
</html>
and javascript as
var mylibrary = {
open : function(){
var id = "10";
}
}
roughly ...

Related

Auto Click on hyperlink

I would like to a HTML code with the following functions if you guys can help , please.
Once the page loads, after 1 second to auto click on a hyperlinked text , how do I do this ? For the new website to be opened in the same window.
I have this code but this one is sending me to a new window and the pop up is blocking - not good
<!DOCTYPE html>
<html>
<body>
<head>
<script>
function autoClick(){
document.getElementById('linkToClick').click();
}
</script>
</head>
<body onload="setTimeout('autoClick();',700);">
<a id="linkToClick" href="http://www.google.com" target="_blank">GOOGLE</a>
</body>
</body>
</html>
Thanks
Instead of using <a href=> you should try just setting the variable window.location.href. So your code should look something like this:
<body onload="window.location.href='http://www.google.com',700);">
https://www.w3schools.com/howto/howto_js_redirect_webpage.asp
Let me preface this by saying this is extremely questionable when it comes to web design, and generally regarded as a shady or bad practice. That said:
$(window).on('load', function(){
window.location = 'http://example.com'
});
OR (vanilla JS)
window.onload = function(){ window.location = 'http://example.com' };
Again, be careful with this. If you want to do something like this, you need a pretty good reason why.
Possible duplicates:
Redirect from an HTML page
HTML redirect on page load

Adding JavaScript code with jQuery.html()

<!DOCTYPE HTML>
<html>
<head>
<script src="js/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function() {
var x="<script>alert('hello world');</script>";
$("#div_one").html(x);
});
</script>
</head>
<body>
<div id="div_one">
</div>
</body>
</html>
Why does this not work? I'd expect the JS code between the script tags to be interpreted and see an alert message ...
What I want to do:
I have written a set of functions that add and delete items from an array depending on the user input (JavaScript). Then, I have a function that draws() a ul-list of the items held in the array. Behind each item, I want to provide a remove link, which calls a JavaScript function that removes the item from the array and then calls drawList() to redraw the list.
If there weren't that security policy, I'd simply do it as in the code shown above.
That is some weird browser bug I believe. For some reason you can't have </script> inside the script block.
Change to
var x="<scr"+"ipt>alert('hello world');</scr"+"ipt>";
Example on jsFiddle
That is not a bug. The problem is here:
<script>
$(document).ready(function() {
var x="<script>alert('hello world');</script>";
$("#div_one").html(x);
});
</script>
The browser thinks the first <script> tag is associated with the </script> inside your code.
As you can see, the code is shown in the DOM instead of executing.
To further prove it, see this example:
http://jsfiddle.net/DerekL/Ah8Qz/
var x = $("<script>").html("alert('hello world');");
$("#div_one").append(x);
If you avoid the </script> closing tag, then there will be no problem because the HTML parser will ignore any open <script> tag inside <script>.
So to sum up,
Browsers does not have security in place to stop scripts being injected into your page.
This is no where near a browser bug.

IE does not read <script> tag, but after refresh works fine

I have a weird bug that is present only in IE (7/8/9/9CV).
FF and Chrome do not have this issue.
I have a pretty big, complex page. In the bottom of the page I have two pieces of JavaScript code right one after another. The first one has no problems, but the second one for some reason is being displayed as a text when I load the page first time. If I just refresh the page without doing anything else - everything works and looks just fine.
Two pieces of JS being generated on a server from two different pagelets so I cannot put them together into one script tag. The first piece of JavaScript code is nothing more but a call to the same function couple of times with different parameters, and the second script is just a declaration of a JSON like object that is being consumed by another function that is defined earlier on the page.
So the page code looks something like this:
<!DOCTYPE html>
<html>
<head>
...
<title>...</title>
</head>
<body>
...
<script type="text/javascript">
//Some javascript that executes perfectly fine every time and is nothing more but just couple of calls to some function
someFunction("param1");
someFunction("param2");
someFunction("param3");
</script>
<script type="text/javascript">
var myObject = {"success":[{"header":"Form successfully submitted","messages":["Some message 1"]}]};
</script>
</body>
</html>
So when a form submitting happens I take this object and use it to display a message on the page. But instead, when user submits the form and it opens the page for the first time, I see this in the bottom of the page:
var myObject= {"success":[{"header":"Form successfully submitted","messages":["Some message 1"]}]};
But when I refresh the page - I do not see that code, but instead I see the message being displayed with values from this object.
When I open the "developer tools" and navigate to the HTML tab, I see that my tag for the second JS piece is shown as commented out!
<!-- sctipt ... -->
But if I refresh the page - it works fine, and in HTML tab of the developer tools it actually shown as a script node that I can expand and see the Javascript code.
Does anyone know what is going on here?!?! This issue has been bugging me for couple of days now!
You should replace
<script type="text/javascipt">
with
<script type="text/javascript">
EDIT :
HTML isn't XHTML. Don't wrap your scripts inside CDATA. Your script elements should be simply like this :
<script type="text/javascript">
var t0_date = new Date();
...
</script>
Change both these:
<script type="text/javascipt">
to:
<script type="text/javascript">
Well, I found an answer to this problem. Well, more of a work around I guess, as this is not something I expected but it works.
Basically, if you put anything between the two script elements - IE wokrs fine!
So what I did was - I put br tag in between and it now works fine. I have no idea why. Perhaps some weird bug in IE rendering engine.
The end result looks like this:
<script type="text/javascript">
//Some javascript that executes perfectly fine every time and is nothing more but just couple of calls to some function
someFunction("param1");
someFunction("param2");
someFunction("param3");
</script>
<br>
<script type="text/javascript">
var myObject = {"success":[{"header":"Form successfully submitted","messages":["Some message 1"]}]};
</script>

AJAX returning a javascript to be parsed results in loss of page contents

So I've been working recently on a script to obfuscate client-side code for protecting intellectual property without interfering with the appearance or interactivity of the resulting page. The process is as follows:
HTTP request comes in, .htaccess redirects (.*) to parse_request.php
parse_request.php creates a "phpURLParser" class whose class variables are essentially copies of the $_SERVER variables
phpURLParser looks at the requested path, and sometimes the host, referer, or other server-side information to determine how to react. There are several possible responses
a. The requested object was a .js or .css file. Pass the file to the YUI Compressor and send the output
b. The requested object is an image or application. Pass the file with no change
c. The requested object contains HTML. Replace every ASCII character with its 2-digit hexadecimal equivalent and send the following javascript:
<script type="text/javascript">
var x="~lots of hex~";
var y="";
for(i=0; i<x.length; i+=2){
y += unescape('%'+x.substr(i,2));
}
document.write(y);
</script>
So the website is replaced by a lot of hex and a small javascript to return the hex to its original form. I have an example of this setup at examples.chikachu.com/colorbox/example1 (I didn't code ColorBox, it's a free jQuery tool that I chose to use since it allowed me to test several different javascript features and make sure they all worked)
Now for the problem:
As it turns out, this works 99% of the time. But AJAX makes it angry. Clicking one of the AJAX examples (under "Other Content Types") will look like it redirects you to a new page. Looking in the address bar or viewing the page source will prove that you're still on the same page, however. Using the Inspect Element tool in Chrome (or Firebug in Firefox) will reveal that the contents of the webpage were entirely replaced by the contents of the AJAX request.
If I modify parse_request.php slightly to allow the file requested by the AJAX to be passed through unharmed, everything works. No problem. So for some reason my script which replaces the string of hex with its meaningful HTML counterpart is overwriting the entire website instead of nicely inserting itself within the confines of a <div> object.
Essentially here's the expected non-obfuscated HTML:
<html>
<head>
...
</head>
<body>
<div id="colorbox">
<INSERT AJAX HERE>
</div>
...
</body>
</html>
With only the AJAX obfuscated, I expect the following:
<html>
<head>
...
</head>
<body>
<div id="colorbox">
<script type="text/javascript">
var x="asdfasdfasdfasdf";
var y="";
for(i=0; i<x.length; i+=2){
y += unescape('%'+x.substr(i,2));
}
document.write(y);
</script>
</div>
...
</body>
</html>
I expect that the document.write() line here will write y at the location of the javascript (within the <div>). If I'm mistaken and that's not how document.write() works, I still expect it to write y at the end of the document. Instead, the entire document is replaced by y. Why is this, and what's my solution?
Answer to your last question:
Calling
document.write('my_precious_html_code');
will append or override text on page depending when it was called (before or after onLoad event). You shouldn't use it any script. Read more about it here: http://javascript.crockford.com/script.html
General answer:
Obfuscating HTML code doesn't make any sense. Just like protecting images by disabling right mouse button in late '90. It took me less then 3 sec to "crack" your obfuscated code and get beautifully formatted HTML. Also your site is rendered in quirks mode which is probably something you don't want.
Try something like this:
<html>
<head>
...
</head>
<body>
<div id="colorbox">
<div id="MYAJAXCONTENT">
</div>
<INSERT AJAX HERE>
</div>
...
</body>
</html>
<html>
<head>
...
</head>
<body>
<div id="colorbox">
<script type="text/javascript">
var x="asdfasdfasdfasdf";
var y="";
for(i=0; i<x.length; i+=2){
y += unescape('%'+x.substr(i,2));
}
document.getElementById('MYAJAXCONTENT').innerHTML = y;
// for the jQuery psychos out there
// $('#MYAJAXCONTENT').html(y);
</script>
</div>
...
</body>
</html>

Write elements into a child iframe using Javascript or jQuery

I have something like this:
<!doctype html>
<html>
<body>
<iframe id="someFrame"></iframe>
</body>
</html>
And I would like to use jQuery to write elements such that the full equivalent HTML would be like this:
<!doctype html>
<html>
<body>
<iframe id="someFrame">
<!-- inside the iframe's content -->
<!-- <html><body> -->
<div>A</div>
<div>B</div>
<div>C</div>
<!-- </body></html> -->
</iframe>
</body>
</html>
Alternatively, any plain-old-Javascript would be fine.
Thanks.
Edit: After a little more research, it seems I am looking for an IE-equivalent of the contentDocument property of an iframe. "contentDocument" is a W3C standard which FF supports, but IE does not. (surprise surprise)
You can do both, you just have to target differently:
var ifrm = document.getElementById('myIframe');
ifrm = ifrm.contentWindow || ifrm.contentDocument.document || ifrm.contentDocument;
ifrm.document.open();
ifrm.document.write('Hello World!');
ifrm.document.close();
After some research, and a corroborating answer from Mike, I've found this is a solution:
var d = $("#someFrame")[0].contentWindow.document; // contentWindow works in IE7 and FF
d.open(); d.close(); // must open and close document object to start using it!
// now start doing normal jQuery:
$("body", d).append("<div>A</div><div>B</div><div>C</div>");
There are two reliable methods to access the document element inside an iframe:
1. The window.frames property:
var iframeDocument = window.frames['iframeName'].document; // or // var iframeDocument = window.frames[iframeIndex].document;
Demo
2. The contentDocument property:
var iframeDocument = document.getElementById('iframeID').contentDocument; // or // var iframeDocument = document.getElementById('iframeID').contentWindow.document;
Demo
I am going out on a limb here and suggest that the answers proposed so far are not possible.
If this iframe actually has a src="somepage.html" (which you ought to have indicated, and if not, what is the point of using iframe?), then I do not think Jquery can directly manipulate html across frames in all browsers. Based on my experience with this kind of thing, the containing page cannot directly call functions from or make any sort of Javascript contact with the iframe page.
Your "somepage.html" (the page that loads in the iframe) needs to do two things:
Pass some kind of object to the containing page that can be used as a bridge
Have a function to set the HTML as you desired
So for example, somepage.html might look like this:
<!doctype html>
<html>
<head>
<script src="jquery.js">
</script>
<script language=JavaScript>
<!--//
var bridge={
setHtml:function(htm) {
document.body.innerHTML=htm;
}
}
$(function() { parent.setBridge(bridge); });
//--></script>
</head>
<body></body>
</html>
and the containing page might look like this:
<!doctype html>
<html>
<head>
<script src="jquery.js">
</script>
<script language=JavaScript>
<!--//
var bridge;
var setBridge=function(br) {
bridge=br;
bridge.setHtml("<div>A</div><div>B</div><div>C</div>");
}
//-->
</script>
</head>
<body><iframe src="somepage.html"></iframe></body>
</html>
This may appear a bit convoluted but it can be adapted in a number of directions and should work in at least IE, FF, Chrome, and probably Safari and Opera...
I have found this to be cross-browser compatible... a little crossing of previous answers and a bit of trial & error of my own. :)
I'm using this for a download of a report, or, if an error (message) occurs, it's displayed in the iFrame. Most of the users will probably have the iFrame hidden, I'm using it multi-functional.
The thing is I have to clear the contents of the iFrame every time I click the report download button - the user can change parameters and it happens there are no results which then is displayed in the iFrame as a message. If there are results, the iFrame remains empty - because the code below has cleared it and the window.open(...) method generates a Content-Disposition: attachment;filename=... document.
var $frm = $("#reportIFrame");
var $doc = $frm[0].contentWindow ? $frm[0].contentWindow.document : $frm[0].contentDocument;
var $body = $($doc.body);
$body.html(''); // clear iFrame contents <- I'm using this...
$body.append('<i>Writing into the iFrame...</i>'); // use this to write something into the iFrame
window.open(Module.PATH + 'php/getReport.php' + Report.queryData, 'reportIFrame');
I do not have a browser that supports contentDocument but I've coded it this way so I'm leaving it. Maybe someone has older browsers and can post compatibility confirmation/issues?

Categories

Resources