opener.document() won't work on CHROME - javascript

Following Script isn't working in CHROME browser, IE is Fine.
I've changed opener.document... to window.opener.document.... but same situation.
It's not closing windows and transfer data to parent page.
function mycoupon() {
window.open("my_coupon3.jsp?amt=<%=pay_price2%>",
'coupon_win',
'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollb‌​ars=yes, resizable=no,width=780,height=540');
}
function sel_coupon(c_id, amt) {
var tot = opener.document.joinform.Org_totalprice.value;
tot = String(Number(tot) - Number(amt));
opener.document.joinform.totalprice.value = tot;
opener.document.joinform.coupon_id.value = c_id;
opener.document.joinform.all["tot"].innerHTML = maskNum(opener.document.joinform.Org_totalprice.value) + "USD - " + maskNum(amt) + " USD <b><font color='red'>Total : " + maskNum(tot) + " USD</font></b> ";
opener.cal_payment_money();
self.close();
}

Define a global variable and assign a reference to the new window then use it in your sel_coupon() function.
Here's an example:
var new_window_handle;
function mycoupon() {
new_window_handle = window.open("my_coupon3.jsp?amt=<%=pay_price2%>",
'coupon_win',
'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollb‌​ars=yes, resizable=no,width=780,height=540');
}
function sel_coupon(c_id, amt) {
var tot = new_window_handle.opener.document.joinform.Org_totalprice.value;
tot = String(Number(tot) - Number(amt));
new_window_handle.opener.document.joinform.totalprice.value = tot;
new_window_handle.opener.document.joinform.coupon_id.value = c_id;
new_window_handle.opener.document.joinform.all["tot"].innerHTML = maskNum(new_window_handle.opener.document.joinform.Org_totalprice.value) + "USD - " + maskNum(amt) + " USD <b><font color='red'>Total : " + maskNum(tot) + " USD</font></b> ";
new_window_handle.opener.cal_payment_money();
self.close();
}
In case you're interested in the reason of this behavior, it's because IE assumes that the default window is the most recent one. So that's why when you run the code on IE it will try to find opener in the new window, but other browsers are a bit more strict (which is better in this case)

Related

I'm trying to declare constants with a dynamically generated name

So, I wanted to automate some of my coding process. I figured maybe I don't have to manually name all the constants that refer to classes, and have a function do that. Here's my code, which, I feel, should work. Of course it doesn't. Should it? If not, why not?
function definitions() {
var allElem = document.querySelectorAll("*"); //Get every HTML element.
for(a = 0; a < allElem.length; a++) { //Iterate through every HTML element.
if (allElem[a].classList.length == 0) { //If an element has no class...
console.log("no var declared, " + a); //...ignore it.
} else { //If it has one or more classes...
for(b = 0; b < allElem[a].classList.length; b++) { //...iterate through the classList.
eval("const " + allElem[a].classList[b] + " = " + "document.getElementsByClassName('" + allElem[a].classList[b] + "');"); //Declare a constant named for the class if refers to
console.log("const " + allElem[a].classList[b] + " = " + "document.getElementsByClassName('" + allElem[a].classList[b] + "');");
}
}
}
console.log(document.getElementsByClassName('clone').length); //This logs 10, which is correct.
console.log(clone.length); // 'Uncaught ReferenceError: clone is not defined'. But... but... I thought I did... :'(
}

Cookie is not being read by Edge or Safari

I'm having a problem where my cookies are not being read by Safari or MS Edge. It works fine in all the other browsers just not in these 2.
Has anyone come across a similar issue? If so how did you manage to sort it out? Thank you.
$('.primary-button.eligibility-button').mousedown(function() {
var selectedCard = $('input[name="cardInterestOption"]:checked').next().text();
var balanceTransferOption = $('input[name="balanceTransferOption"]:checked').next().text().replace(/[a-z]/g,'');
var annualIncome = parseFloat($( "input[name='annualIncome']").val());
var otherIncome = parseFloat($( "input[name='otherIncome']").val());
var totalIncome = annualIncome + otherIncome;
document.cookie = "creditCardSelectorEligibility=" + selectedCard + "; path=/;";
document.cookie = "creditCardBalanceTransfer=" + balanceTransferOption + "; path=/;";
document.cookie = "creditCardTotalIncome=" + totalIncome + "; path=/;";
});
(function() {
var page = "";
var percentage = "NA";
var path = location.pathname;
if(/results/.test(path)){
page = "Success";
var results = "";
var percent = $(".results-banner:eq(0)").text();
if(/\b[0-9]{2}/.test(percent)){
results = percent.match(/\b[0-9]{2}/)[0]
}
}
else if(/verify/.test(path)){
page = "Verify";
}
else if(/problem/.test(path)){
page = "Problem";
}
else if(/noteligible/.test(path)){
page = "Not Eligible";
}
else if(/unavailable/.test(path)){
page = "Unavailable";
}
var selectedCard = bt_cookie('yrd_creditCardSelectorEligibility')
var balanceTransferOption = bt_cookie('yrd_creditCardBalanceTransfer')
var totalIncome = bt_cookie('yrd_creditCardTotalIncome')
return page + "|" + selectedCard + "|" + balanceTransferOption + "|" + totalIncome + "|" + results;
})();
What we have found happen sometimes, is that the page loads too quick for the cookie to be created. So we have had to change the way the Cookies get created. For instance you can change the code to create the Cookie as the user interacts with the form. ie: If the select a button or fill in a field. Capture the cookie there, rather than at the end of the page where the customer has to click the submit. Hopefully this makes sense?

CasperJS Load next page in loop

I've been working on a script which collates the scores for a list of user from a website. One problem is though, I'm trying to load the next page in the while loop, but the function is not being loaded...
casper.then(function () {
var fs = require('fs');
json = require('usernames.json');
var length = json.username.length;
leaderboard = {};
for (var ii = 0; ii < length; ii++) {
var currentName = json.username[ii];
this.thenOpen("http://www.url.com?ul=" + currentName + "&sortdir=desc&sort=lastfound", function (id) {
return function () {
this.capture("Screenshots/" + json.username[id] + ".png");
if (!casper.exists(x("//*[contains(text(), 'That username does not exist in the system')]"))) {
if (casper.exists(x('//*[#id="ctl00_ContentBody_ResultsPanel"]/table[2]'))) {
this.thenEvaluate(tgsagc.tagNextLink);
tgsagc.cacheCount = 0;
tgsagc.
continue = true;
this.echo("------------ " + json.username[id] + " ------------");
while (tgsagc.
continue) {
this.then(function () {
this.evaluate(tgsagc.tagNextLink);
var findDates, pageNumber;
pageNumber = this.evaluate(tgsagc.pageNumber);
findDates = this.evaluate(tgsagc.getFindDates);
this.echo("Found " + findDates.length + " on page " + pageNumber);
tgsagc.checkFinds(findDates);
this.echo(tgsagc.cacheCount + " Caches for " + json.username[id]);
this.echo("Continue? " + tgsagc["continue"]);
this.click("#tgsagc-link-next");
});
}
leaderboard[json.username[id]] = tgsagc.cacheCount;
console.log("Final Count: " + leaderboard[json.username[id]]);
console.log(JSON.stringify(leaderboard));
} else {
this.echo("------------ " + json.username[id] + " ------------");
this.echo("0 Caches Found");
leaderboard[json.username[id]] = 0;
console.log(JSON.stringify(leaderboard));
}
} else {
this.echo("------------ " + json.username[id] + " ------------");
this.echo("No User found with that Username");
leaderboard[json.username[id]] = null;
console.log(JSON.stringify(leaderboard));
}
});
while (tgsagc.continue) {
this.then(function(){
this.evaluate(tgsagc.tagNextLink);
var findDates, pageNumber;
pageNumber = this.evaluate(tgsagc.pageNumber);
findDates = this.evaluate(tgsagc.getFindDates);
this.echo("Found " + findDates.length + " on page " + pageNumber);
tgsagc.checkFinds(findDates);
this.echo(tgsagc.cacheCount + " Caches for " + json.username[id]);
this.echo("Continue? " + tgsagc["continue"]);
return this.click("#tgsagc-link-next");
});
}
Ok, looking at this code I can suggest a couple of changes you should make:
I don't think you should be calling return from within your function within then(). This maybe terminating the function prematurely. Looking at the casperjs documentation, the examples don't return anything either.
Within your while loop, what sets "tgsagc.continue" to false?
Don't use "continue" as a variable name. It is a reserved word in Javascript used for terminating an iteration of a loop. In your case this shouldn't be a problem, but its bad practice anyhow.
Don't continually re-define the method within your call to the then() function. Refactor your code so that it is defined once elsewhere.
We ended up having to scope the function, so it loads the next page in the loop.
This is mainly because CasperJS is not designed to calculate scores, and it tries to asynchronously do the calculation, missing the required functions

Why is Firebug unable to detect some JavaScript?

I have written JavaScript outside the <body> end tag. Firebug is unable to detect the JavaScript and I am unable to detect the JavaScript error.
Here is my code:
</body>
<script type="text/javascript">
function displayIFrameContent()
{
var iFrame = document.getElementById("link");
var if1= "<iframe src='http://leadmarket.hol.es/forms/solar-power.php?adv_id=" + <?php echo($fetch_users_data['id']); ?>;
var if2= "<iframe src='http://leadmarket.hol.es/forms/kitchen-installation.php?adv_id=" + <?php echo($fetch_users_data['id']); ?>;
var if3= "<iframe src='http://leadmarket.hol.es/forms/conservatory.php?adv_id=" + <?php echo($fetch_users_data['id']);; ?>;
var host = document.getElementById("host");
var subId = document.getElementById("subid");
var errorClass = "box form-validation-error border-width-2";
if(host.value == "")
changeClass("host", errorClass);
if(host.value != "")
{
var iFrameEnd = " width='280' height='330' frameborder='0' scrolling='no'></iframe>";
var leadTypeSelect = document.getElementById("leadType");
var leadTypeValue = leadTypeSelect.options[leadTypeSelect.selectedIndex].value;
iFrame.value = "";
if(leadTypeValue == 1)
iFrame.value = if1 + "&" + "sub_id=" + subId.value + "&source=" + host.value + "'" + iFrameEnd;
if(leadTypeValue == 2)
iFrame.value = if2 + "&" + "sub_id=" + subId.value + "&source=" + host.value + "'" + iFrameEnd;
if(leadTypeValue == 3)
iFrame.value = if3 + "&" + "sub_id=" + subId.value + "&source=" + host.value + "'" + iFrameEnd;
}
}
function changeClass(id, classname)
{
document.getElementById(id).setAttribute("class", classname);
}
</script>
</html>
Your help will be appreciated. Thanks in advance!
The code above contains PHP tags, which cause some syntax errors. In this case the Script panel just shows a message "No Javascript on this page". You should make sure they are interpreted by PHP before they are output to the browser.
Also JavaScript syntax errors are listed within the Console Panel. Make sure you have the option Show JavaScript Errors checked to see them.
Furthermore there's a detailed description about script debugging available within the Firebug wiki.
Sebastian

Converting firefox javascript to IE javascript

I've been trying to get some AJAX code that runs fine in FireFox to run in IE.
I'm running into some trouble with updating some tables in the script though. I've seen numerous other people have similar issues, but none of the solutions they've found have worked for me. The problem occurs first on the line
qe3Table.innerHTML =
"<tr>\n" +
" <th>Name</th>\n" +
" <th>Status</th>\n" +
" <th>View Status</th>\n" +
"</tr>\n";
Where I'm getting the error "'null' is null or not an object"
I'm pretty sure that all of my other errors are of the same type as this one, my AJAX script and some accompanying javascript is below.
<script type="text/javascript">
<!--
//obtains the box address for a QE3 on the system for the given index
function getQE3BoxAddressHash(index)
{
var retVal = 0x00000100; //initial value for QE3 boxes
retVal |= (index & 0x000000FF);
return retVal;
}
//obtains the box address for a QED on the system for the given index
function getQEDBoxAddressHash(index)
{
var retVal = 0x00001300; //initial value for QED boxes
retVal |= ((index & 0x0000000F) << 4);
retVal |= ((index & 0x000000F0) >> 4);
return retVal;
}
-->
</script>
<script type="text/javascript">
<!--
var textSocket;
function fillTables()
{
if(textSocket.readyState != 4)
return;
var qe3Table = document.getElementById("QE3_TABLE");
var qedTable = document.getElementById("QED_TABLE");
var rawData = textSocket.responseText.split("::::");
var qe3Data = new Array();
var qedData = new Array();
var qe3Index = 0;
var qedIndex = 0;
for(var item in rawData)
{
if(rawData[item].indexOf("QA") != -1)
{
qe3Data[qe3Index++] = rawData[item];
}
else if(rawData[item].indexOf("QED") != -1)
{
qedData[qedIndex++] = rawData[item];
}
}
qe3Table.innerHTML =
"<tr>\n" +
" <th>Name</th>\n" +
" <th>Status</th>\n" +
" <th>View Status</th>\n" +
"</tr>\n";
qedTable.innerHTML =
"<tr>\n" +
" <th>Name</th>\n" +
" <th>Status</th>\n" +
" <th>View Status</th>\n" +
"</tr>\n";
for(var value in qe3Data)
{
var components = qe3Data[value].split("-");
if(components.length != 3)
continue;
qe3Table.innerHTML +=
"<tr>\n" +
" <td>" + components[0] + "-" + components[1] +"</td>\n" +
" <td>" +
((components[2].toUpperCase() === "ONLINE")?
"<font color=\"green\"><b>ONLINE</b></font>":
"<font color=\"red\"><b>OFFLINE</b></font>")+
"</td>\n" +
" <td>\n <input type=\"button\" onclick=\"window.location='system_status.php?boxAddress=" + getQE3BoxAddressHash(value).toString(16) + "'\" value='View Status for " + components[0] + "-" + components[1] +"'></input> </td>\n" +
"</tr>\n";
}
for(var value in qedData)
{
var components = qedData[value].split("-");
if(components.length != 3)
continue;
qedTable.innerHTML +=
"<tr>\n" +
" <td>" + components[0] + "-" + components[1] +"</td>\n" +
" <td>" +
((components[2].toUpperCase() === "ONLINE")?
"<font color=\"green\"><b>ONLINE</b></font>":
"<font color=\"red\"><b>OFFLINE</b></font>")+
"</td>\n" +
" <td>\n <input type=\"button\" onclick=\"window.location='system_status.php?boxAddress=" + getQEDBoxAddressHash(value).toString(16) + "'\" value='View Status for " + components[0] + "-" + components[1] +"'></input> </td>\n" +
"</tr>\n";
}
}
function initAjax()
{
try
{
// Opera 8.0+, Firefox, Safari
textSocket = new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer Browsers
try
{
textSocket = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
textSocket = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
// Something went wrong
alert("A browser error occurred.");
return false;
}
}
}
textSocket.onreadystatechange=fillTables
}
function reloadTables()
{
textSocket.open("GET","ajax_scripts/get_connected_boxes.php",true);
textSocket.send(null);
}
function init()
{
initAjax();
reloadTables();
}
window.onload=init();
-->
</script>
The problem is probably with:
var qe3Table = document.getElementById("QE3_TABLE");
If you're running this script before the body is loaded, that won't exist. Check to see if that variable has anything in it.
I Tried both of your guys' fixes but they didn't seem to help. In the end, I converted all calls of the form:
qe3TableNew.innerHTML = ("<tr>\n" +" <th>Name</th>\n" +" <th>Status</th>\n" +" <th>View Status</th>\n" +"</tr>\n");
to
var row;
var cell;
var text;
var font;
row = document.createElement("tr");
qe3TableNew.appendChild(row);
cell = document.createElement("th");
row.appendChild(cell);
text = document.createTextNode("Name");
cell.appendChild(text);
cell = document.createElement("th");
row.appendChild(cell);
text = document.createTextNode("Status");
cell.appendChild(text);
cell = document.createElement("th");
row.appendChild(cell);
text = document.createTextNode("View Status");
cell.appendChild(text);
This seemed to solve it, so I believe it has to do with IE's inability to handle changes to innerHTML.
Thanks for the help guys.
At least one issue (which could produce the above symptoms) is the line:
window.onload=init();
Hint: the () operator executes the function immediately and evaluates to the return value. This in turn may allow the XHR handler (in certain situations) to fire at a time when the DOM may not be ready.
Happy coding.

Categories

Resources