JavaScript function in an external file won't run - javascript

'use strict';
function phone() {
if( navigator.userAgent.match(/Android/gi)
|| navigator.userAgent.match(/webOS/gi)
|| navigator.userAgent.match(/iPhone/gi)
|| navigator.userAgent.match(/iPad/gi)
|| navigator.userAgent.match(/iPod/gi)
|| navigator.userAgent.match(/BlackBerry/gi)
|| navigator.userAgent.match(/Windows Phone/gi)
){
return true;
}
else {
return false;
}
}
<!doctype html>
<html>
<head>
<link rel=stylesheet id="style" href='style.css'/>
</head>
<body>
<script src="phone.js"></script>
<script>
phone();
</script>
</body>
</html>
The external function won't run when the page opens why is that? I even tried doing onload but nothing happened. When the page opens it should print in the console either true or false but absolutely nothing is printed.

You are not actually printing the result. You need to change to this:
<script>
console.log( "Is phone: " + phone() );
</script>

Related

Problem: Javascript iframe send the postMessage() before iframe completed loading

I have iframe in parent.html. Child.html sending the postMessage('documnent.cookie','*') to the parent window.
The problem is postMessage() send 'null'. postMessage() is triggered before iframe loading is completely done. I have to postMessage() to Parent window only if iframe completely loads the data.
Here is my code: parent.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<body id="Body" style="background-color:Silver">
<iframe id ="CA_FRAME_0" src="http://localhost/ibmcognos/bi/child.html" style="display:none"></iframe>
<script type="text/javascript">
window.addEventListener("message", function (e){
if(e.data == null){
alert('fail');
}else{
alert('sucess');
document.cookie="key=" +e.data + ";expires=0;path=/";
}
}, false);
</script>
<div id="arcContainer" class="arcContainer"></div>
<script type="text/javascript">
ARCPLAN.language = "XXX";
ARCPLAN.application = "lv02";
ARCPLAN.startDocName = "application.apa";
ARCPLAN.arcCgiSite = "http://localhost/.....";
</script>
</body>
</html>
//child.html
<!DOCTYPE html> <html> <head>
<title>COOKIE</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge" /> </head> <body>
<script type="text/javascript">
function getCookie(name) { var arg = name + "="; var alen = arg.length; var clen = document.cookie.length; var i = 0; while(i < clen) { var j = i
+ alen; if(document.cookie.substring(i, j) == arg)
return getCookieVal(j); i = document.cookie.indexOf(" ", i) + 1; if(i == 0)
break; } return null; }
function getCookieVal(offset) { var endstr = document.cookie.indexOf(";", offset); if(endstr == -1) endstr = document.cookie.length; return document.cookie.substring(offset, endstr); }
**parent.postMessage(getCookie("key"), "*");** </script>
**<iframe id ="CA_FRAME" src="http://localhost/ibmcognos/bi/" style="display: none;" ></iframe>** - *this url make the redirect from here and set the cookie, it takes time*
</body> </html>
Kindly provide me some suggestions. Thanks.
In this case we have a webpage A need to load another webpage B through iframe.
page A is loaded. we can add a custom event to listen page B load event.
page A code:
const iframeWin = document.getElementById('h5-iframe').contentWindow;
window.addEventListener(
'message',
(e) => {
const { data } = e;
console.log('receive page load', data);
if (data.pageLoaded) {
iframeWin.postMessage(youdata, '*');
}
},
false,
);
page B code:
window.addEventListener(
'message',
(e) => {
console.log('receive youdata', data);
const { data } = e;
},
false,
);
// after register listen function send this message to page A.
window.parent.postMessage({ pageLoaded: true }, '*');
Add an onload event to your iFrame:
<iframe id ="CA_FRAME" src="http://localhost/ibmcognos/bi/" onload="onCaFrameLoad(this)" style="display: none;"></iframe>
Then you can run JS code only after the frame has completely loaded:
function onCaFrameLoad() {
// wrap your post in this function
};
This way, the code will only run once the frame has finished loading.
PoC:
parent.html
<html>
<body>
PARENT- I get data from child
<br /><br />
<iframe id ="CA_FRAME_0" src="child.html"></iframe>
</body>
</html>
child.html
<html>
<body>
CHILD - I send data to parent - but only after CA_FRAME has loaded
<br /><br />
<iframe id ="CA_FRAME" src="inner.html" onload="onCaFrameLoad(this)"></iframe>
<script>
function onCaFrameLoad() {
alert('iframe has loaded! now you can send data to the parent');
};
</script>
</body>
</html>
inner.html
<html>
<body>
INNER - I load all my content, then the onCaFrameLoad function in child.html runs
<script>
alert('My Name is INNER - I load all my content first');
</script>
</body>
</html>

Question: How to do so that (null) does not appear in (document.write)

How can I change my code so that if the user presses on cancel the following code will write document.write("#DELETE") or simply leave an empty space?
<!DOCTYPE html>
<html>
<body>
<script language="JavaScript">
var a = prompt("Put a text");
if (a === null || !a) {
document.write("");
} else {
document.write( "Your Text is: " + a );
}
</script>
</body>
</html>
var radiuuss = prompt("Please set the radius");
document.write("Press 1 to put the code or press 2 to clear section");
if (radiuuss === null) {
document.write("#DELETE");
} else {
// document write a message with the value of the radiuuss.
}

Why is index.html being treated as JSON? Unexpected token < at position 0

I am trying to use Qunit to make unit tests for this html. The error I'm getting is Uncaught SyntaxError: Unexpected token < in JSON at position 0. It's pointing to the "<" in <!DOCTYPE html> Clearly this isn't JSON, but it thinks it is, but I'm not sure why.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Pinpoint Test</title>
<link rel="stylesheet" href="https://code.jquery.com/qunit/qunit-2.0.0.css">
<script type="text/javascript" src="https://code.jquery.com/qunit/qunit-2.0.0.js"></script>
<script type="text/javascript" src="lib/jquery-3.0.0.min.js"></script>
<script type="text/javascript" src="jshamcrest.js"></script>
<script type="text/javascript" src="core.js"></script>
<script type="text/javascript" src="integration.js"></script>
<script type="text/javascript" src="jsmockito-1.0.4.js"></script>
<script type="text/javascript" src="lib/handlebars-v4.0.5.js"></script>
<script type="text/javascript" src="bootstrap.min.js"></script>
<script src="pinpoint.js"></script>
<script src="pinpointTest.js"></script>
</head>
<body>
<div id="qunit"></div>
<div id="qunit-fixture">
//a lot more html
</body>
</html
It says Source: at window.onerror (https://code.jquery.com/qunit/qunit-2.0.0.js:322:11)
qunit-2.0.0.js:
// Cover uncaught exceptions
// Returning true will suppress the default browser handler,
// returning false will let it run.
window.onerror = function( error, filePath, linerNr ) {
var ret = false;
if ( onErrorFnPrev ) {
ret = onErrorFnPrev( error, filePath, linerNr );
}
// Treat return value as window.onerror itself does,
// Only do our handling if not suppressed.
if ( ret !== true ) {
if ( QUnit.config.current ) {
if ( QUnit.config.current.ignoreGlobalErrors ) {
return true;
}
QUnit.pushFailure( error, filePath + ":" + linerNr );
} else {
//322 QUnit.test( "global failure", extend( function() {
QUnit.pushFailure( error, filePath + ":" + linerNr );
}, { validTest: true } ) );
}
return false;
}
return ret;
};
My guess is that missing > at the end of your html file is just a typo in this example? I think you might need to put all these <script> tags at the end of your <body> instead of in the <head>... QUnit wants that <div id="qunit"></div> tag to put its UI in, and as it is, your tests are trying to run before the HTML ever loads. Give that a try, but if it doesn't work, can you simplify your test to just a simple assert.equall(1, 1) to see if that works? You could also update the question with your actual tests if you want us to look at them.

Javascript some function not working

Currently inside my javascript there are two functions which are working - function isChecked(checkbox, sub1) and function change(obj) - while the other two functions under $(document).ready() are not working.
There's no console error nor do I think the codes are wrong. Somehow this two functions aren't running at all.
How do I run a console log to debug further ?
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Order CDs</title>
</head>
<body>
<script type = "text/javascript">
function isChecked(checkbox, sub1) {
var button = document.getElementById(sub1);
if (checkbox.checked === true) {
button.disabled = "";
} else {
button.disabled = "disabled";
}
}
function change(obj) {
var selectBox = obj;
var selected = selectBox.options[selectBox.selectedIndex].value;
var retCustDetails = document.getElementById("retCustDetails");
var tradeCustDetails = document.getElementById("tradeCustDetails");
if(selected === 'ret'){
retCustDetails.style.display = "block";
tradeCustDetails.style.display = "none";
}
else{
retCustDetails.style.display = "none";
tradeCustDetails.style.display = "block";
}
}
$(document).ready(function(){
$('#termsChkbx').change(function(){
if($(this).is(':checked'))
{
$(this).parent('p').css('color','black');
}
else
{
$(this).parent('p').css('color','red');
}
});
$(document).on("click",".chosen",function() {
var sum=0;
var chk=$(this).find("input");
if(chk.is(':checked')) {
sum = sum + parseInt(chk.val());
} else {
sum = sum - parseInt(chk.val());
}
$('#total').val(sum);
});
});
</script>
You can run console.log(someVariableName) to output the value of any variable to the console. In most browsers you open the deveoper tools with F12 where you can see the output.
You will most likely also find a useful debugger there that allows you to run and observe the execution of your program step by step.
You would use console.log("My log message") or console.log(myLogVariable).
In your example I'd say you forgot to load JQuery. Add this to your <head> section.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">
</script>
Use <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"> </script> to import jQuery library before first use of $. I've added it for you in head section.
<head>
<meta charset="UTF-8" />
<title>Order CDs</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"> </script>
</head>
<body>
Now your code is error free. For debugging, you can use console.log("Anything") or console.log("Anything"). This will get printed in console tab. Press F12 to open debugger. Click on "Console" tab. Here you will get all error logs, and custom logs, if used console.log("my own message"). Keyboard shortcuts: ctrl+shift+j, ctrl+shift+i or f12

In IE why does document.open fail but tempDocument.open succeed?

In an iframe when loading content dynamically, the sequence document.open, document.write, and document.close fails in IE 9, 10, and 11 but succeeds in other browsers. However, if I assign document to a temporary variable and then do open, write, close, IE succeeds. Why is this?
(Yes, I know that there are better options besides document.open/write/close, like jquery and DOM construction, but I am curious why this fails.)
The following files show the problem:
index.htm
<!DOCTYPE html>
<html>
<head>
<title>Top Window</title>
</head>
<body>
<p>Top Window</p>
<div id="testDiv" style="width: 100%;">
<iframe src="frame.htm" style="width: 100%;"></iframe>
</div>
</body>
</html>
frame.htm
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<p>Waiting...</p>
</body>
</html>
script.js
'use strict';
var getPage = function() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if( (this.readyState == 4) && (this.status == 200) ) {
writePage( this, "" + this.responseText );
}
};
xmlhttp.open("GET", "content.htm", true);
xmlhttp.send();
};
var writePage = function( xmlhttp, pageContent ) {
var tempDocument = document;
document.open( "text/html" );
document.write( pageContent );
document.close();
};
getPage();
content.htm
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>This is my written content.</h1>
</body>
</html>
In the writePage function, this sequence does not work (the document.open call does not return):
document.open( "text/html" );
document.write( pageContent );
document.close();
However, using the temporary reference like this:
tempDocument.open( "text/html" );
tempDocument.write( pageContent );
tempDocument.close();
works fine.

Categories