I get a blank page on Firefox (only h2 showing) - javascript

This is the page written, and I should be getting "I can print", but I only get the title, and the rest of the page is blank. Where is the mistake?
<!DOCTYPE html>
<html>
<head>
<title>Object exercise 4</title>
</head>
<body>
<h2>Object exercise 4</h2>
<script type = "text/javascript">
function PrintStuff(myDocuments)
{
this.documents = myDocuments;
}
PrintStuff.prototype.print=function()
{
console.log(this.documents);
}
var newObj = new PrintStuff("I can print");
newObj.print();
</script>
</body>
</html>

console.log() is not what is used to add content to the page. There are several ways of solving your problem - I have added one of those as a code snippet:
function PrintStuff(myDocuments) {
this.documents = myDocuments;
}
PrintStuff.prototype.print = function() {
var paragraph = document.createElement("p");
paragraph.innerText = this.documents;
document.body.appendChild(paragraph);
console.log(this.documents); // this only prints to the browser console (and throws an exception in IE if the console was not opened before)
}
var newObj = new PrintStuff("I can print");
newObj.print();
<h2>Object exercise 4</h2>
If you do not know what the browser console is, press [F12] in the browser (it is really helpful) or see What are browser developer tools? (all the stuff at developer.mozilla.org is awesome).

Related

Can't set body.innerHTML of new "about:blank"-window in Firefox (window.open())

This is a Q&A-style-Thread because I couldn't find someone with this problem/with a solution.
Case:
You have a javascript where you open a new window with window.open('about:blank', ...) and you want to set its content by setting myWindowReference.document.body.innerHTML = SOMETHING.
Problem:
Works fine in Chrome, Edge, IE, Opera but not in several (perhaps all?) versions of Firefox. The page remains white but the log-message of console.dir(myWindowReference.document.body.innerHTML); is correct.
Example Code:
<!doctype html>
<html>
<head>
<script>
window.onload = () => {
let wind = window.open('about:blank', 'someName', 'resizable,scrollbars');
wind.document.body.innerHTML = "HALLO, das ist ein TEST";
wind.document.title = "TEST";
wind.focus();
console.log("wind.document.body.innerHTML:");
// OUTPUT IS CORRECT
// but page is blank
console.dir(wind.document.body.innerHTML);
}
</script>
</head>
<body></body>
</html>
Solution
My guess is that Firefox isn't waiting internally until the window reference is fully there and therefore doesn't update the GUI but updates it somehow internally so that console.dir(wind.document.body.innerHTML); has the correct output anyway. I found out that a solution is using a timeout so that Firefox has enough time to fully build the window reference internally.
<!doctype html>
<html>
<head>
<script>
window.onload = () => {
let wind = window.open('about:blank', 'someName', 'resizable,scrollbars');
// [B] DOES WORK
window.setTimeout(() => {
wind.document.body.innerHTML = "HALLO, das ist ein TEST";
wind.document.title = "TEST";
}, 1) // USING A TIMEOUT IS THE SOLUTION
/* [A] DOESN't WORK
wind.document.body.innerHTML = "HALLO, das ist ein TEST";
wind.document.title = "TEST";
*/
wind.focus();
console.log("wind.document.body.innerHTML:");
console.dir(wind.document.body.innerHTML);
/*
This log message is in either way ([A] and [B]) correct in Firefox.
With [A] there is no content and no title set to the window, althrough it is visible.
With [B] it works. Seems like Firefox is internally not waiting for the right reference/
until the window is opened.
*/
}
</script>
</head>
<body></body>
</html>
Solution 2 (Better Solution):
Found out that there is no need to use "about:blank" in window.open() for an empty page. Because "about:blank" is a special page in Firefox this might be the reason for the bug. Just leave it empty and it works.
<!doctype html>
<html>
<head>
<script>
window.onload = () => {
let wind = window.open('', 'someName', 'resizable,scrollbars');
wind.document.body.innerHTML = "HALLO, das ist ein TEST";
wind.document.title = "TEST";
wind.focus();
}
</script>
</head>
<body></body>
</html>

Visualize YouTube player iframe on a Chrome extension [duplicate]

I have created a JavaScript variable and when I click on the button it should increment by 1, but its not happening.
Here's manifest.json.
{
"name":"Facebook",
"version":"1.0",
"description":"My Facebook Profile",
"manifest_version":2,
"browser_action":{
"default_icon":"google-plus-red-128.png",
"default_popup":"hello.html"
}
}
Here is the code for the html page
<!DOCTYPE html>
<html>
<head>
<script>
var a=0;
function count()
{
a++;
document.getElementById("demo").innerHTML=a;
return a;
}
</script>
</head>
<body>
<p id="demo">=a</p>
<button type="button" onclick="count()">Count</button>
</body>
</html>
I want the extension to show me the value of a and increment it by one each time I click on the extension or the button
Your code is not working because it violates the default Content Security Policy. I've created a screencast of one minute to show what's wrong:
First, I've shown how to debug the problem. Right-click on your popup button, and click on "Inspect popup". After doing that, you will see the following error message:
Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' chrome-extension-resource:".
This explains that your code is not working, because it violates the default CSP: Inline JavaScript will not be executed. To solve the problem, you have to remove all inline JavaScript from your HTML file, and put it in a separate JS file.
The result is shown below:
hello.html (popup page)
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id="demo">=a</p>
<button type="button" id="do-count">Count</button>
<script src="popup.js"></script>
</body>
</html>
popup.js
var a=0;
function count() {
a++;
document.getElementById('demo').textContent = a;
}
document.getElementById('do-count').onclick = count;
Note that I've replaced innerHTML with textContent. Learn to use textContent instead of innerHTML when you intend to change the text. In this simple example it does not matter, but in more complex applications, it might become a security issue in the form of XSS.
Change your onclick:
onclick="count"
Or change your count function to something like this:
function count()
{
var demo = document.getElementById("demo");
return function() {
demo.innerHTML = ++a;
}
}
Here is a nice demo I put together:
Code (this assumes that you add id="the_button" to your button):
window.onload = function () {
var button = document.getElementById("the_button");
button.onclick = count();
function count() {
var a = 0;
var demo = document.getElementById("demo");
return function () {
demo.innerHTML = ++a;
}
}
}
Demo: http://jsfiddle.net/maniator/ck5Yz/

JavaScript prompt() firing before content is rendered

This is my first time working with prompt(). I have completed the assignment to the specifications given by the teacher, however I am really annoyed that the prompt() gets called before the content in the background gets called (I even used window.onload = function() {blah}; but it still gets called before the content is displayed.
The link to the page is http://homepage.cs.uiowa.edu/~csoultz/ and click on lab4
This is not a huge concern more so a curiosity of mine. I have been researching it for the last few hours and have found nothing. I don't want to load anymore libraries and if it is not possible without a library please let me know. Thank you in advance for any help
here is the code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Work Week Calculator</title>
<link rel="stylesheet" href="mySite.css">
<script>
function askquestion(question,answer){
var userAnswer = prompt(question.toString());
if(userAnswer!=null) return userAnswer.toLowerCase()===answer.toLowerCase();
};
</script>
</head>
<body>
<h1>A Simple Quiz</h1>
<p><output id="result"></output></p>
<script>
window.onload = function() {
var trivia=[["Which is the most widely spoken language in the world?","Mandarin"],
["The art of paper folding is known as what?","Origami"],
["Bubble tea originated in which country?","Taiwan"]
];
var correct=0;
var total=trivia.length;
for(i=0;i<trivia.length;i++){
if(askquestion(trivia[i][0],trivia[i][1])){
alert("Correct!");
correct++;
}
else{
alert("Sorry. The correct answer is "+trivia[i][1].toString());
}
}
var resultElement = document.getElementById("result");
resultElement.innerHTML = "You got "+correct.toString()+" out of "+total.toString()+" questions correct";
};
</script>
</body>
</html>
I was able to wrap my function in a setTimeout with a timeout value of 10 and the issue was fixed in chrome.
window.onload = setTimeout(function() {
//Do Stuff Here
},10);

Can't call function from body onload (uncaught reference error: start is not defined) javascript

I have a body onload calling a function in javascript. I Have tried many things, but the console just prints to the error log: uncaught reference error: start is not defined. I think it might be a malfunction, please notify me if it works for you. My code is as follows:
<!DOCTYPE html>
<html>
<head>
<title>Monster Invasion</title>
<script type="javascript">
var hur;
var monsters = 10;
var objective = false;
var health = 100;
var damage = 30;
var sheild = false;
var ea = 1;
function start() {
setTimeout(hurt,4000)
}
function hurt() {
var newhelth = health - damage;
health = newhelth;
document.getElementById("healtw").innerHTML = health;
start();
}
function kill() {
if(monsters > 0) {
monsters--;
document.getElementById("monster1").src="dead.jpg"
setTimeout(next,2000)
}else {
objective = true;
document.location="endoflevel.html";
}
}
function next() {
document.getElementById("monster1").src="monster.jpg"
}
}
</script>
</head>
<body onload="start()">
<p id="healtw"></p>
<embed src="guide_first_level.mp3" type="audio/mp3" hidden="true" autostart="true">
<a id="st" onclick="kill()"><img id="monster1" src="monster.jpg"></a>
<p id="ada"></p>
Activate sheild
</body>
</html>
your script type is wrong.
try like this
<script type="text/javascript">
</script>
However, you don't need to mention script type. just use a plain script tag.
like this
<script>
</script>
One more thing to add that before the end of the script tag, you gave an extra }.
just remove it
function next() {
document.getElementById("monster1").src="monster.jpg"
}
} // <-- just remove this bracket
</script>
Well for some of you, who are using external js file, please just check to see whether you linked your file or not :)... because I had the same error but as I looked through my code ..I hadn't linked the file then!
just in case you came here looking for an answer too!
There are two problems with your code.
javascript is not a valid type for the script in the browser. Browsers know text/javascript, but not just javascript, that is why your code is not being executed. Change the type attribute or remove it at all (for text/javascript is the default value).
You have an extra bracket } at the end of the code. Remove it and your code will work fine.
There are 3 errors:
Correct the type of your script tag
There is an extra } at the end of your code
Instead of using onload() for body tag, you should better use window.onload as follows in order to make sure your start() function is run once document is ready:
...
<head>
<title>Monster Invasion</title>
<script type="text/javascript">
window.onload = function(){
// Put all your code here
// And at the end run start() function
start();
}
</script>
</head>
<body>
...

Range Selection and Mozilla

I would like to specify that firefox select a range. I can do this easily with IE, using range.select();. It appears that FFX expects a dom element instead. Am I mistaken, or is there a better way to go about this?
I start by getting the text selection, converting it to a range (I think?) and saving the text selection. This is where I'm getting the range from initially:
// Before modifying selection, save it
var userSelection,selectedText = '';
if(window.getSelection){
userSelection=window.getSelection();
}
else if(document.selection){
userSelection=document.selection.createRange();
}
selectedText=userSelection;
if(userSelection.text){
selectedText=userSelection.text;
}
if(/msie|MSIE/.test(navigator.userAgent) == false){
selectedText=selectedText.toString();
}
origRange = userSelection;
I later change the selection (successfully). I do so by range in IE and by a dom ID in ffx. But after I do that, I want to set back the selection to the original selection.
This works like a charm in IE:
setTimeout(function(){
origRange.select();
},1000);
I would like to do something like this in FFX:
var s = w.getSelection();
setTimeout(function(){
s.removeAllRanges();
s.addRange(origRange);
},1000);
Unfortunately, FFX has not been cooperative and this doesn't work. Any ideas?
The short answer is: IE and other browsers differ in their implementations of selecting text using JavaScript (IE has its proprietary methods). Have a look at Selecting text with JavaScript.
Also, see setSelectionRange at MDC.
EDIT: After making a little test case, the problem becomes clear.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>addRange test</title>
<style>
#trigger { background: lightgreen }
</style>
</head>
<body>
<p id="test">This is some (rather short) text.</p>
<span id="trigger">Trigger testCase().</span>
<script>
var origRange;
var reselectFunc = function () {
var savedRange = origRange;
savedRange.removeAllRanges();
savedRange.addRange(origRange);
};
var testCase = function () {
// Before modifying selection, save it
var userSelection,selectedText = '';
if(window.getSelection){
userSelection=window.getSelection();
}
else if(document.selection){
userSelection=document.selection.createRange();
}
selectedText=userSelection;
if(userSelection.text){
selectedText=userSelection.text;
}
if(/msie|MSIE/.test(navigator.userAgent) === false){
/* you shouldn't do this kind of browser sniffing,
users of Opera and WebKit based browsers
can easily spoof the UA string */
selectedText=selectedText.toString();
}
origRange = userSelection;
window.setTimeout(reselectFunc, 1000);
};
window.onload = function () {
var el = document.getElementById("trigger");
el.onmouseover = testCase;
};
</script>
</body>
</html>
When testing this in Firefox, Chromium and Opera, the debugging tools show that after invoking removeAllRanges in reselectFunc, both savedRange and origRange are reset. Invoking addRange with such an object causes an exception to be thrown in Firefox:
uncaught exception: [Exception...
"Could not convert JavaScript argument
arg 0 [nsISelection.addRange]"
nsresult: "0x80570009
(NS_ERROR_XPC_BAD_CONVERT_JS)"
location: "JS frame ::
file:///home/mk/tests/addrange.html ::
anonymous :: line 19" data: no]
No need to say that in all three browsers no text is selected.
Apparently this in intended behaviour. All variables assigned a (DOM)Selection object are reset after calling removeAllRanges.
Thank you Marcel. You're right, the trick is to clone the range, then remove the specific original range. This way we can revert to the cloned range. Your help led me to the below code, which switches the selection to elsewhere, and then back according to a timeout.
I couldn't have done it without you, and grant you the correct answer for it :D
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>addRange test</title>
<style>
#trigger { background: lightgreen }
</style>
</head>
<body>
<p id="switch">Switch to this text</p>
<p id="test">This is some (rather short) text.</p>
<span id="trigger">Trigger testCase().</span>
<script>
var origRange;
var s = window.getSelection();
var reselectFunc = function () {
s.removeAllRanges();
s.addRange(origRange);
};
var testCase = function () {
// Before modifying selection, save it
var userSelection,selectedText = '';
if(window.getSelection){
userSelection=window.getSelection();
}
else if(document.selection){
userSelection=document.selection.createRange();
}
selectedText=userSelection;
if(userSelection.text){
selectedText=userSelection.text;
}
if(/msie|MSIE/.test(navigator.userAgent) === false){
/* you shouldn't do this kind of browser sniffing,
users of Opera and WebKit based browsers
can easily spoof the UA string */
selectedText=selectedText.toString();
}
origRange = userSelection;
var range = s.getRangeAt(0);
origRange = range.cloneRange();
var sasDom = document.getElementById("switch");
s.removeRange(range);
range.selectNode(sasDom);
s.addRange(range);
window.setTimeout(reselectFunc, 1000);
};
window.onload = function () {
var el = document.getElementById("trigger");
el.onmouseover = testCase;
};
</script>
</body>
</html>

Categories

Resources