JavaScript: Using document.write(); - javascript

I'm attempting to create a new HTML doc using document.write INSIDE another document.write in JavaScript.
I know this is a painful way to do it (and feel free to rewrite the code with the desired output), but here it is:
var newDoc = document.open("text/html", "replace");
newDoc.write("<html><head><title>Failure!</title></head><body><h5>js::error 5015 &&syn.0</h5><p>In Quantum Mechanisms exists a quantum state known as quantum superposition - the state of being two things at once given a random subatomic event that may or may not occur.</p><p>A famous experiment by Erwin Schrödinger, a cat was placed in a box along with a poison flask that would kill the cat, only activating if a subatomic change was detected (which is completely random). The thought experiment brought forth the idea of the cat being <em>dead</em> and <em>alive</em> at the same exact time, but you aren't able to know which it is. So in theory, by opening the box and finding that the cat is dead, you have essentially killed the cat yourself.</p><p>Quantum Mechanics have been applied to the button you just clicked. The choice was yours on whether or not to click it, and you did not know where you would end up. You can say that it would have unlocked a new upgrade, or break the game, but since you clicked the button, you therefore must have broken the game yourself. Just like that, curiosity killed the cat. Sorry, quantum superposition is pretty terrible. Fortunately, you can click this button below to continue on your journey.</p><button onclick=\"var newDoc = document.open(\"text/html\", \"replace\"); newDoc.write(\"<html><head><title>Double Fail</title></head><body><p>No seriously, quantum mechanics are pretty bad. :)</p></body></html>\"); newDoc.close();\">Continue</button></body></html>");
newDoc.close();
As you can see, the button is not outputting the information clearly. Not sure what i'm doing wrong.

A lot of escaping needs to happen:
var newDoc = document.open("text/html", "replace");
newDoc.write('<html><head><title>Failure!</title></head><body><h5>js::error 5015 &&syn.0</h5><p>In Quantum Mechanisms exists a quantum state known as quantum superposition - the state of being two things at once given a random subatomic event that may or may not occur.</p><p>A famous experiment by Erwin Schrödinger, a cat was placed in a box along with a poison flask that would kill the cat, only activating if a subatomic change was detected (which is completely random). The thought experiment brought forth the idea of the cat being <em>dead</em> and <em>alive</em> at the same exact time, but you aren\'t able to know which it is. So in theory, by opening the box and finding that the cat is dead, you have essentially killed the cat yourself.</p><p>Quantum Mechanics have been applied to the button you just clicked. The choice was yours on whether or not to click it, and you did not know where you would end up. You can say that it would have unlocked a new upgrade, or break the game, but since you clicked the button, you therefore must have broken the game yourself. Just like that, curiosity killed the cat. Sorry, quantum superposition is pretty terrible. Fortunately, you can click this button below to continue on your journey.</p><button onclick="var newDoc = document.open(\'text/html\', \'replace\'); newDoc.write(\'<html><head><title>Double Fail</title></head><body><p>No seriously, quantum mechanics are pretty bad. :)</p></body></html>\'); newDoc.close();">Continue</button></body></html>');
newDoc.close();
Here's where the problem starts:
</p><button onclick=\"var newDoc = document.open(\"text/html\"
^^ starting onclick ^^ ending it

var newDoc = document.open("text/html", "replace");
newDoc.write("<html><head><title>Failure!</title></head><body>Button:<button onclick=\"var newDoc = document.open("text/html", "replace"); newDoc.write("<html><head><title>Double Fail</title></head><body><p>Button clicked.</p></body></html>"); newDoc.close();\">Continue</button></body></html>");
newDoc.close();
Your quoting is bad. The generated HTML will break on ", you need to employ HTML escaping (") inside your onclick attribute, not JavaScript escaping (\") at that point.

Related

How do I stop my webpage cleanly in Firefox?

I have created an IIS MVC webpage.
Users find that if they leave it open overnight it is in some "frozen" state in the morning and it has also frozen any other tabs that might be open in the brower.
Therefore, they have to kill the whole browser window and log into my webpage again.
How can I cleanly shutdown(or put into nice state) my webpage at 10PM?
I have tried the following, which works on Chrome, but not Firefox:
setTimeout(function () { quitBox('quit') }, millisTill10);
function quitBox(cmd) {
if (cmd == 'quit') {
open(location, '_self').close();
window.close();
}
return false;
}
I am happy to leave the tab there - but put it into some kind of clean, dead state, that would not interfere with the other tabs.
I have tried to catch the error to fix it - but I have no idea what is causing it to freeze. The code below does NOT catch it:
window.onerror = function(error, url, line) {
alert('Inform please ERR:'+error+' URL:'+url+' L:'+line);
};
Fuller version:
window.onerror = function (errorMsg, url, lineNumber, column, errorObj) {
var stackTrace = "Not available";
try {
stackTrace = errorObj.prototype.stack
} catch (e) {
try {
stackTrace = errorObj.stack
} catch (e) {
try {
stackTrace = errorObj.error.stack
} catch (e) {
}
}
}
alert('Please inform of Error: ' + errorMsg + ' Script: ' + url + ' Line: ' + lineNumber
+ ' Column: ' + column + ' StackTrace: ' + errorObj + ' ST: ' + stackTrace);
}
Debugging a Browser Death
Rather than looking at how to "kill" the tab, it might be worth looking at why the application is dying in the first place. Firefox is a single-process browser (currently), but it has a lot of safety checks in place to keep the process running, which means that there's a pretty short list of things that can actually "kill" it.
First off, let's cross off some things that can't kill it: Plugins like Java and Flash. These run in a separate process already (if they're running at all):
So at most, if they're runaways, they'll kill themselves but the rest of the browser will still be running.
Second, you're not seeing memory warnings. Firefox is pretty good about displaying an error dialog when JavaScript consumes too much memory, so if you're not seeing that, odds are really good it's not an out-of-memory issue.
The Most Likely Causes
What that leaves is a fairly short list of possibilities:
Browser bug (unlikely, but we'll list it anyway)
Browser add-on/extension bug
Infinite loop in JavaScript
Infinite recursion in JavaScript
Not-quite-infinite-but-close-enough loop/recursion in JavaScript
Now let's cross those off.
A browser bug is unlikely, but possible. But, as a general rule when debugging, assume it's your code that's broken, not the third-party framework/tool/library around you. There are a thousand really sharp Mozilla devs working daily to kill any bugs in it, which means that anything you see failing probably has your code as a root cause.
A browser extension/add-on bug is possible, but if you're seeing this on everybody's computers, odds are good that they all have different configurations and it's not an issue with an extension/add-on. Still, it's probably worth testing your site in a fresh Firefox install and letting it sit overnight; if it isn't broken in the morning, then you have a problem with an extension/add-on.
A true infinite loop or infinite recursion is also pretty unlikely, based on your description: That would likely be readily detectable at a much earlier stage after the page has been loaded; I'd expect that at some point, the page would just suddenly go from fully responsive to fully dead — and, more importantly, the browser has an "Unresponsive script" dialog box that it would show you if it was stuck in a tight infinite loop. The fact that you're not seeing an "Unresponsive script" dialog means that the browser is still processing events, but likely processing them so slowly or rarely that it might as well be completely frozen.
Not Quite Infinite Death
More often than not, this is the root cause of "dead page" problems: You have some JavaScript that works well for a little bit of data, and takes forever with a lot of data.
For example, you might have code on the page tracking the page's behavior and inserting messages about it into an array, like this, so that the newest messages are at the top: logs.unshift(message) That code works fine if there are relatively few messages, and grinds to a halt when you get a few hundred thousand.
Given that your page is dying in the middle of the night, I'd wager dollars to donuts that you have something related to regular tracking or logging, or maybe a regular Ajax call, and when it kicks off, it performs some action that has overall O(n^2) or O(n^3) behavior — it only gets slow enough to be noticeable when there's a lot of data in it.
You can also get similar behavior by accidentally forcing reflows in the DOM. For example, we had a chunk of JavaScript some years ago that created a simple bulleted list in the UI. After it inserted each item, it would measure the height of the item to figure out where to put the next one. It worked fine for ten items — and died with a hundred, because "measure the height" really means to the browser, "Since there was a new item, we have to reflow the document to figure out all the element sizes before we can return the height." When inserting, say, the 3rd item, the browser only has to recompute the layout of the two before it. But when inserting the 1000th item, the browser has to recompute the layout of all 999 before it — not a cheap operation!
I would recommend you search through your code for things like this, because something like it is probably your root cause.
Finding the Bug
So how do you find it, especially in a large JavaScript codebase? There are three basic techniques:
Try another browser.
Divide and conquer.
Historical comparison.
Try Another Browser
Sometimes, using another browser will produce different behavior. Chrome or IE/Edge might abort the JavaScript instead of dying outright, and you might get an error message or a JavaScript console message instead of a dead browser. If you haven't at least tried letting Chrome or IE/Edge sit on the page overnight, you're potentially ignoring valuable debugging messages. (Even if your production users will never use Chrome or IE/Edge, it's at least worth testing the page in them to see if you get different output that could help you find the bug.)
Divide-and-Conquer
Let's say you still don't know what the cause is, even bringing other browsers into the picture. If that's the case, then I'd tackle it with the approach of "divide and conquer":
Remove half of the JavaScript from the page. (Find a half you can remove, and then get rid of it.)
Load the page, and wait for it to die.
Analyze the result:
If the page dies, you know the problem is still in the remaining half of the code, and not in the half you removed.
If the page doesn't die, you know the problem is in the half you removed, so put that code back, and then remove the good half of the code so you're left with only the buggy code in the page.
Repeat steps 1-3, cutting the remaining JavaScript in half each time, until you've isolated the bug.
Since it takes a long time for your page to die, this may make for a long debugging exercise. But the divide-and-conquer technique will find the bug, and it will find it faster than you think: Even if you have a million lines of JavaScript (and I'll bet you have far less), and you have to wait overnight after cutting it in half each time, it will still take you only twenty days to find the exact line of code with the bug. (The base-2 logarithm of 1,000,000 is approximately 20.)
Historical Analysis
One more useful technique: If you have version control (CVS, SVN, Git, Mercurial, etc.) for your source code, you may want to consider testing an older, historical copy of the code to see if it has the same bug. (Did it fail a year ago? Six months ago? Two years ago?) If you can eventually rewind time to before the bug was added, you can see what the actual change was that caused it, and you may not have to hunt through the code arbitrarily in search of it.
Conclusion
In short, while you can possibly put a band-aid on the page to make it fail gracefully — and that might be a reasonable short-term fix while you're searching for the actual cause — there's still very likely a lot more you can do to find the bug and fix it for real.
I've never seen a bug I couldn't eventually find and fix, and you shouldn't give up either.
Addendum:
I suppose for the sake of completeness in my answer, the simple code below could be a suitable "kill the page" band-aid for the short term. This just blanks out the page if a user leaves it sitting for eight hours:
<script type='text/javascript'><!--
setTimeout(function() {
document.location = 'about:blank';
}, 1000 * 60 * 60 * 8); // Maximum of 8 hours, counted in milliseconds
--></script>
Compatibility: This works on pretty much every browser with JavaScript, and should work all the way back to early versions of IE and Netscape from the '90s.
But if you use this code at all, don't leave it in there very long. It's not a good idea. You should find — and fix! — the bug instead.
If the tab was opened by JavaScript, then you may close it with JavaScript.
If the tab was NOT opened by JavaScript, then you may NOT close it with JavaScript.
You CAN configure FireFox to allow tabs to be closed by JavaScript by navigating to about:config in the URL bar and setting dom.allow_scripts_to_close_windows to true. However, this will have to be configured on a machine-by-machine basis (and opens up the possibility of other websites closing the tab via JavaScript).
So:
Open the tab via JavaScript so that it can then be closed by JavaScript
or
Change a FireFox setting so that JavaScript can close a tab.
PS. I'd also recommend taking a look at https://developers.google.com/web/tools/chrome-devtools/memory-problems/ to try to help identify memory leaks (if the application has a memory leak) or having the web app ping the server every minute for logging purposes (if the application is breaking at an unknown time at the same time every night).
As was mentioned in other comments you don't need to find how to close, you need how to avoid "freezing".
I suggest:
Collect statistic what browser/browsers fall
Collect metrics from browser that fail you can use window.performance and send logs to the server in timeout (I haven't tried, timeout can freeze before you have logs you need)

Random Quote Generator Dilemma

My code works fine on my pen at Codepen... Random Quote Generator at Codepen
BUT...
I've been going over this at my site, but I'm just not seeing what the issue is. Random QuoteGenerator at my personal site
var quote = document.getElementById('quote');
var click = document.getElementById('click');
var quoteList = ["'You will never be happy if you continue to search for what happiness consists of. You will never live if you are looking for the meaning of life.'",
"'Do not read, as children do, to amuse yourself, or like the ambitious, for the purpose of instruction. No, read in order to live.'",
"'Two things are infinite: the universe and human stupidity; and I'm not sure about the universe.'",
"'A life spent making mistakes is not only more honorable, but more useful than a life spent doing nothing.'",
"'In vain have I struggled. It will not do. My feelings will not be repressed. You must allow me to tell you how ardently I admire and love you.'",
"'It is better to remain silent at the risk of being thought a fool, than to talk and remove all doubt of it.'",
"'Have you ever been in love? Horrible isn't it? It makes you so vulnerable. It opens your chest and it opens up your heart and it means that someone can get inside you and mess you up.'",
"'The problem with the world is that the intelligent people are full of doubts, while the stupid ones are full of confidence.'",
"'Ok. You fuck me, then snub me. You love me, you hate me. You show me a sensitive side, then you turn into a total asshole. Is this a pretty accurate description of our relationship.'",
"'I love sleep. My life has the tendency to fall apart when I'm awake, you know?.'",
"'If I had a flower for every time I thought of you...I could walk through my garden forever.'",
"'Keep away from people who try to belittle your ambitions. Small people always do that, but the really great make you feel that you, too, can become great.'",
"'Never tell the truth to people who are not worthy of it.'",
"'The one you love and the one who loves you are never, ever the same person.'",
"'Becoming fearless isn't the point. That's impossible. It's learning how to control your fear, and how to be free from it.'",
"'I hope she'll be a fool -- that's the best thing a girl can be in this world, a beautiful little fool.'"];
var randomQuote = function(){
var twitter = document.getElementById('twitter');
var index = Math.floor(Math.random()*quoteList.length);
twitter.href = "https://twitter.com/intent/tweet?text=" + encodeURI(quoteList[index]);
quote.innerHTML = quoteList[index];
};
randomQuote();
click.addEventListener('click', randomQuote, false);
So the question is, what is going on? Same code, quotes aren't working on my personal site. Any help would be greatly appreciated. Thanks.
In your HTML script element, you're referencing the script with a href attribute when it should be src.
Also your code is executing before the DOM exists, move the Javascript to the end of the HTML body section.
<script src="//six03.com/quotes/script.js" type="text/javascript"></script>
</body>
</html>
You're attempting to bind the events prior to the page finishing its load. The simplest fix is to just move the script tag to the bottom of the page and load it at the end of the body.
Otherwise you can use a library to be sure the page is loaded or bind to an event. In jQuery that would be using the $(document).ready(function(){}) event.

How to write a twitter-like RichText box for mentioning entities?

After weeks of trying and testing to find a solution for my needs I admit that I still have no idea how I can solve this problem.
It sounds simple: I want that a user is able to mention things in a text area similar to twitter.
The problem is that I can't seem to manage it to make it work. Every browser has its own specialties which are coming into my way and break things. I have tried multiple different attempts but none of them worked even on a single browser completely.. mixing text and HTML appears to be incredibly hard to do.
So here I am. Asking you guys for any kind of help. Whether it's a library you can recommend me that is already doing what I need here, or if you did something similar and can tell me what exactly you did to make this work on multiply browsers.
My current solution looks something like this: Hitting # will insert a input text field into a div contenteditable everything is working nice so far unless the whole thing is the first element of a row. If the caret is also at position 0 and the user hits Enter, then something dies inside the browser which removes the whole input box without further notice or any events - at least not on Chrome. That was the most promising solution that I was able to come up with. Don't think I didn't try to save it by inserting e.g. a native Text with a zero-whitespace-character but that doesn't work either. It works better - but not completely.
I'm really frustrated by now and this is holding my whole project back which has this key feature that has to work properly - mainly because the information put there is going to be persisted as XML but that is a completely different story.
I really hope somebody can help me to get a solution for this. Bear in mind that I am actually using GWT 2.8.0 but I would not mind to use/wrap a JavaScript library at this point ..

Acrobat's Javascript console is not working

Moving from InDesign to Acrobat now, I need to automate a very simple task. I'll eventually use BridgeTalk to have an InDesign script call Acrobat X and have it do a couple of simple things. To this end I've been reading up on how to script Acrobat. Unfortunately, it does not seem anywhere as simple as scripting InDesign or Illustrator.
For one thing, the ExtendScript Toolkit is now useless since Acrobat has a built-in "Javascript Console". This would be perfectly fine, except that my console seems to be completely broken. Once I launched it (and it was hellacious just trying to figure that out), I type in a simple 3 + 4 in the console and press Command+Enter, as noted in Thom Parker's guide on AcrobatUsers. (I don't have a fancy Mac extended keyboard with a numeric keypad, so I have to use Command+Enter.)
Nothing happens.
I've tried other things, such as selecting the code first, pressing Control+Enter instead, using a different line of code such as console.println("Hello.");, etc. Nothing I do seems to work. What am I doing wrong?
Finally got my question answered over on Adobe's forums. I thought I had tried everything, but it turns out that I had not even tried a simple Shift + Enter. Hard to believe, since I thought I'd tried every possible key combination already, but I cannot deny the facts. Since I only had the small Apple keyboard without the numeric keypad, I suppose this is the only way to get Enter instead of Return from that key. At any rate, the answer is now known!
It seems to be command-return on MacOS 10.13.6 But thanks for the hint above.

Need a cool hotkey for my hidden website-login

I am developing a CMS. One of the greatest everyday annoyances when working with it is that when you are on a front-end page, not logged in, and want to make a change, you need to go to the back-end login first, log in, and then navigate to the page you want to change.
I would like to introduce a smart little function that pops up a log-in screen when you hit a certain key combination. I have already set this up with double Ctrl. I have come to realize, though, that I hit that key so frequently that the login pops up unwanted, something that must not happen of course.
So, I am asking for your ideas for a clever key combination.
I am looking for a key combination that is:
Elegant and easy to memorize (this is why I liked double Ctrl very much)
Time considerations (Press key X, then Y after 1 second) are possible
Must not be mapped to any browser function of course. I realize this cannot be excluded 100% but obviously, Ctrl+A or Alt+Tab would be nonstarters.
Works on all keyboards (Mac included, but I'm willing to handle the apple special keys)
Extremely unlikely to be hit accidentally
Other clever ideas like simple mouse gestures are also welcome.
It can be argued that this poses a decrease in security, as the URL to the back-end login is made available in front-end pages and loses the additional protection by being obscure. I may address that later using a cookie that identifies CMS users' machines but it is not the issue right now.
Oh you just KNOW you have to go for the Konami Code!
There are several websites that implement it - take a look at this list.
I know it's not the simplest, but it does have the geek factor ;)
Why not just have a "Editor Login" link at the bottom of the page?
It won't be any less secure and will be a lot easier to use. I can see the solution you are trying to use causing all kinds of odd problems down the road...
If you really really want it "hidden", you can just make it white text on a white background or something.
What about the simple ` key at the top left corner of your keyboard? This is often used in games to get into a console mode (counter strike, left 4 dead, etc). It is mac/windows/linux compatible and shouldn't interfere with anything in the browser.

Categories