HTML onload script triggered too many times? - html

I created a simple ASP.Net html page. I would like to put a password check, ONLY when the page is initially loaded, I did it with a script and assigned the tag onload to the body. The problem is, that the password check is triggered every time I press a button. Why does this happens? How can I execute that password check ONLY when you open the page?
Thanks in advance.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="FotoDiClasse.aspx.cs" Inherits="FotoDiClasse" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Choose your sweatshirt</title>
<!-- password control -->
<script>
var password;
var pass1 = "1234";
var firstTime = true;
function checkPassword()
{
if (firstTime)
firstTime = false;
password = prompt("Enter password to access the site", '');
if (password != pass1) window.location = "http://www.google.com";
}
</script>
</head>
<body onload="checkPassword()">
<form id="form1" runat="server">
<div>
<asp:Button ID="CreateButton" runat="server" Text="Create" Width="240px" OnClick="CreateButton_Click" />
<asp:Button ID="SendButton" runat="server" Text="Send" Width="240px" OnClick="SendButton_Click" />
</div>
</form>
</body>
</html>
This "first time" flag doesn't work

It is called PostBack. Every time a Button is pressed the Page performs a Form Post (PostBack). That means the page is reloaded.
With the snippet below you can call a JavaScript function only when the page is first loaded.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "runScript", "alert('This is not a PostBack');", true);
}
}

It happens because every time you press a button your page is loaded and onload() method is called and hence every time that method is called.
To overcome this problem you need to set some sort of function that check whether your page is loaded first time or not to do this you can use cookie to store that session.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="FotoDiClasse.aspx.cs" Inherits="FotoDiClasse" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Choose your sweatshirt</title>
<!-- password control -->
<script>
var password;
var pass1 = "1234";
var firstTime = true;
function checkPassword()
{
if (firstTime)
firstTime = false;
password = prompt("Enter password to access the site", '');
if (password != pass1) window.location = "http://www.google.com";
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="CreateButton" runat="server" Text="Create" Width="240px" OnClick="CreateButton_Click" />
<asp:Button ID="SendButton" runat="server" Text="Send" Width="240px" OnClick="SendButton_Click" onblur="checkPassword()"/>
</div>
</form>
</body>
</html>

Related

reCAPTCHA Unexpected token in JSON at position 0

We use reCAPTCHA ver 2 as checkbox "I am not bot". Since from 2020-11-05 19:23:00Z during our page loading we get exception:
recaptcha__ru.js:211 Uncaught (in promise) SyntaxError: Unexpected token in JSON at position 0
at JSON.parse (<anonymous>)
at recaptcha__ru.js:211
at recaptcha__ru.js:209
at Array.<anonymous> (recaptcha__ru.js:132)
at Array.<anonymous> (recaptcha__ru.js:208)
at GM.$ (recaptcha__ru.js:211)
at Array.<anonymous> (recaptcha__ru.js:253)
at QS.next (recaptcha__ru.js:416)
at y (recaptcha__ru.js:355)
Exception occurs in https://www.google.com/recaptcha/api2/anchor?ar=1&k=6LcOyt8ZAAAAAD9WJMwwwvgvSGp8Bi0zWYS-FMX5&co=aHR0cDovL2JsYWNrYmlyZDo0ODA4MA..&hl=ru&v=1AZgzF1o3OlP73CVr69UmL65&size=normal&cb=a79dhaz0etu
Our page has not been changed. The reCAPTCHA breaks unexpectedly in one moment. On other page reCAPTCHA is still working (may be it is important the working page is a embedded inside iframe).
Any hints? What went wrong?
UPDATED
We try to isolate reCAPTCHA inside iframe in our JSP page as #user2384519 suggested:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<%# taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%# taglib uri="http://richfaces.org/a4j" prefix="a4j"%>
<%# taglib uri="http://richfaces.org/rich" prefix="rich"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Captcha test</title>
<script>
function extractRecaptchaResponse() {
var c = document.getElementById('g-recaptcha-isolator');
if (c) {
var src = c.contentWindow.document
.getElementById('g-recaptcha-response');
if (src) {
var target = document.getElementById('g-recaptcha-response');
target.value = src.value;
}
}
return true;
}
</script>
</head>
<body>
<h:form id="g-recaptcha-form">
<h:panelGroup>
<iframe id="g-recaptcha-isolator" src="/recaptcha.htm"
onload='javascript:(function(o){o.style.height=o.contentWindow.document.body.scrollHeight+"px";}(this));'
style="height: 78px; width: 100%; border: none; overflow: hidden;">
</iframe>
</h:panelGroup>
<textarea id="g-recaptcha-response" name="g-recaptcha-response"
style="display: none"></textarea>
<h:panelGroup>
<h:commandLink onclick="extractRecaptchaResponse()"
actionListener="#{recaptcha.submit}">
<span>Submit</span>
</h:commandLink>
</h:panelGroup>
</h:form>
</body>
</html>
recaptcha.htm:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<script src="https://www.google.com/recaptcha/api.js"></script>
</head>
<body>
<div class="g-recaptcha" data-sitekey="xxxxxxx"></div>
and it solves the problem with JSON error, but reCAPTCHA shows popup with image selector and iframe cuts the popup.
If you are using Prototype.js:
The Prototype JS library overrides the method reduce in the class Array.
The issue is resolved if you just add the following script after all imports (preferentially after the body tag):
Array.prototype.reduce = function(callback, initialVal) {
var accumulator = (initialVal === undefined) ? undefined : initialVal;
for (var i = 0; i < this.length; i++) {
if (accumulator !== undefined)
accumulator = callback.call(undefined, accumulator, this[i], i, this);
else
accumulator = this[i];
}
return accumulator;
};
We also faced the same issue on 11/5. For quick fix, we have embedded recapcha in iframe. It was getting block by ajax4jsf/framework.pack.js
We had the same problem, then identified that the issue was a conflict caused by another minified js file loaded on the same page.
We trimmed down what js was loaded on the page down to a bare minimum, eliminating the collision, and now it works fine again.

iframe can access element of parents with different origin(domain + port)

I know a iframe tag can access to parent element with same domain + ports.
However, what if parent and iframe has different domain + port ?
i.e.
parent's domain is http://aaa.com:63342, and iframe domain is http://aaa.com:9080.(Please note that they have different ports)
Both of pages have <meta http-equiv='X-Frame-Options' content='ALLOWAll'> in their headers.
first, parent frame call iframe with form submit. like...
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='X-Frame-Options' content='ALLOWAll'>
<title>ParentWindows with aaa.com:63342</title>
</head>
<body>
<form name='form' method='post' id='form' action=''>
<input type='text' name='greetings' value='Hello from the otherside'>
</form>
<script>
document.form.target = 'iframe';
document.form.action = 'http://aaa.com:9080//inFrame.jsp';
document.form.submit();
</script>
</body>
<iframe src="" name='iframe'></iframe>
</html>
Then a server returns like below in jsp
<%
response.setHeader("X-Frame-Options", "ALLOWAll");
String greetings = request.getParameter("greetings");
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='X-Frame-Options' content='ALLOWAll'>
<title>iframe with aaa.com:9080</title>
</head>
<body>
<div>
greetings message : <%= greetings %>
</div>
</body>
<script>
var div = document.createElement('div');
div.textContent = 'Echo Hello';
parent.document.body.appendChild(div);
</script>
</html>
It is simple version of the situation what I am in. However, when I do like this, browser console shows error like..
Uncaught SecurityError: Blocked a frame with origin "http://localhost:9080" from accessing a frame with origin "http://localhost:63342". Protocols, domains, and ports must match.
Now I am doubting with this method(calling different hosts between iframe and parent) is possible at first place... Is it possible?
How can I make this works?
Thanks a lot
Detour to original frame.
something like...
original page with aaa.com:63342/original.html is
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='X-Frame-Options' content='ALLOWAll'>
<title>ParentWindows with aaa.com:63342</title>
<script>
function setGreetings(greetings){
document.getElementById('greetings').value = greetings;
}
</script>
</head>
<body>
<form name='form' method='post' id='form' action=''>
<input type='text' id='greetings' name='greetings' value='Hello from the otherside'>
</form>
<script>
document.form.target = 'iframe';
document.form.action = 'http://aaa.com:9080//inFrame.jsp';
document.form.submit();
</script>
</body>
<iframe src="" name='iframe'></iframe>
</html>
Then page(jsp) which imported into the original page(inside of iframe) looks like... I can call aaa.com:9080/inFrame.jsp
<%
response.setHeader("X-Frame-Options", "ALLOWAll");
String greetings = request.getParameter("greetings");
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='X-Frame-Options' content='ALLOWAll'>
<title>iframe with aaa.com:9080</title>
</head>
<body>
<div>
greetings message : <%= greetings %>
</div>
<iframe id='iframe' src="http://localhost:63342/third.html?greetings=<%= greetings %>"></iframe>
</body>
</html>
This is the third frame aaa.com:63342/third.html, final
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='X-Frame-Options' content='ALLOWALL'>
<title>ACCESS TO TOP FRAME on localhost:63342</title>
</head>
<body>
<script>
function setGrandfather(){
var greetings = getParams()['greetings'];
window.top.setGreetings(greetings);
}
//parsing parameters
function getParams() {
var param = new Array();
var url = decodeURIComponent(location.href);
url = decodeURIComponent(url);
var params;
params = url.substring( url.indexOf('?')+1, url.length );
params = params.split("&");
var size = params.length;
var key, value;
for(var i=0 ; i < size ; i++) {
key = params[i].split("=")[0];
value = params[i].split("=")[1];
param[key] = value;
}
return param;
}
</script>
</body>
</html>
What happens here
the original page has iframe which has different domain
the second page(iframed in the original page) also has an iframe which has same origin with original page
the second page will send data to its iframe(the third page) with post/get. I wish it could access other frame element via parent.document or iframe.contentDocument.document, but these will be blocked by SAMEORIGIN policy.
In third page you can access functions and elements of the original frame since they have same origin(domain + ports).
CAUTION
frames can not communicate directly
only those pages has common url, possible to set sub domain via document.domain

JSP simple program

I am trying to do a JSP program where there is a number and a button. Upon clicking the button, the number above increments. I need to use sessions in this program.
This is the code I did:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title> Welcome </title>
</head>
<body>
<%
// check if there already is a "Counter" attrib in session
AddCount addCount = null;
int test = 0;
String s;
try {
s = session.getAttribute("Counter").toString();
} catch (NullPointerException e){
s = null;
}
if (s == null){
// if Counter doesn't exist create a new one
addCount = new AddCount();
session.setAttribute("Counter", addCount);
} else {
// else if it already exists, increment it
addCount = (AddCount) session.getAttribute("Counter");
test = addCount.getCounter();
addCount.setCounter(test);
addCount.addCounter(); // increment counter
session.setAttribute("Counter", addCount);
}
%>
<%! public void displayNum(){ %>
<p> Count: <%= test %> </p>
<%! } %>
<input TYPE="button" ONCLICK="displayNum()" value="Add 1" />
</body>
</html>
The result is that every time I run the program, the number increments.. however I do not want this to happen.. I want the number to increment upon clicking the button :/ What am I doing wrong?
Thanks for any help. Would be very much appreciated!
A schematic JSP, as it could have been done.
Here I assume that the page is named "counter.jsp" and that the AddCount class resides in a package "mypkg".
JSP encodings can be set in the HTML header lines, before the first HTML browser text.
For ISO-8859-1 you may actually use encoding Windows-1252, with extra chars, like special comma-like quotes. Even MacOS browsers will accept these.
Here I check whether the button was clicked, as whether the form parameter "somefield" is present. (There are other possibilities.)
session="true" is crucial here.
<%#page contentType="text/html; charset=Windows-1252"
pageEncoding="Windows-1252"
session="true"
import="java.util.Map, java.util.HashMap, mypkg.AddCount" %>
<%
// Check if there already is a "Counter" attrib in session
AddCount addCount = (AddCount)session.getAttribute("Counter");
if (addCount == null) {
// If Counter doesn't exist create a new one
addCount = new AddCount();
session.setAttribute("Counter", addCount);
}
// Inspect GET/POST parameters:
String somefield = request.getParameter("somefield");
if (field != null) {
// Form was submitted:
addCount.addCounter(); // increment counter
}
int count = addCount.getCounter();
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome - counter.jsp</title>
</head>
<body>
<p> Count: <%= count %></p>
<form action="counter.jsp" method="post">
<input type="hidden" name="somefield" value="x" />
<input type="submit" value="Add 1" />
</form>
</body>
</html>

Sessions JSP button click

Hi I want to do a JSP program where there is a number displayed and a button. When the user clicks this button the number above it increments. I want to include sessions in this program.
What I have done is this:
This is the form in html:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>My Form</title>
</head>
<body>
<%! public void displayNum(){ %>
Number: <%=session.getAttribute("Counter") %>
<%! } %>
<FORM METHOD=POST ACTION="getcount.jsp">
<button TYPE="button" ONCLICK= "displayNum()">Add 1</button>
</FORM>
</body>
</html>
and this is myJSP file:
<%
AddCount addCount = new AddCount();
addCount.setCounter(addCount.addCounter(addCount.getCounter()));
int counter = addCount.getCounter();
session.setAttribute("Counter", counter);
%>
where AddCount is a java class with a variable counter, setter and getter and a function to increase the counter - addCount(num); all I'm getting when running the file is a button without any text in it :/
I've been trying over and over again. Can someone help me please?
Thankss!
You are adding java code in html, which is not possible.
Second thing even if you are having a static int counter in AddCount it wont work as many user s may use this page and expect only one increment for their each click.
So what you should do is write a jsp file like this index.jsp
<%Integer counter = (Integer)request.getSession().getAttribute("counter")
if(counter==null) {counter=0;}
counter ++;
request.getSession().setAttribute("counter",counter);
%>
<div>counter=<%=counter%></div><br>
+1
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>My Form</title>
</head>
<body>
function displayNum()
{
<%
AddCount addCount = new AddCount();
addCount.setCounter(addCount.addCounter(addCount.getCounter()));
int counter = addCount.getCounter();
session.setAttribute("Counter", counter);
%>
document.getElementById("demo").innerHTML="<%=session.getAttribute("Counter")%>";
}
<p id="demo"> {number will be displayed here} </p>
<button TYPE="button" ONCLICK= "displayNum()">Add 1</button>
</body>
</html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script src="jquery.js"></script>
<title>My Form</title>
</head>
<body>
<script>
$(document).ready(function() {
$("button").click(function() {
$("#div1").load("increament.jsp");
});
});
</script>
<div id="div1"> {number will be displayed here} </div>
<button>Add 1</button>
</body>
</html>
and increament.jsp file :
<%
int count;
if (session.getAttribute("Counter") == null) {
count = 1;
} else {
count = (Integer) session.getAttribute("Counter");
count++;
}
session.setAttribute("Counter", count);
out.println(session.getAttribute("Counter"));
%>

Google visualization is small inside AJAX Control Toolkit Tab Control

I'm trying to use a google visualisation, the column chart, inside an asp.net AJAX Toolkit Tab Control, but I'm having small (literally) problems.
If I add the visualisation to the tab that's displayed by default when the page loads, the bar chart displays correctly, however, if I add the same control to another tab and reload the page, when I click on the other tab, the control is displayed, but its tiny and unusable.
Here's some code for a test.aspx page that illustrates the problem:
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="TestProject._Default" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', { packages: ['columnchart'] });
</script>
<script type="text/javascript">
function drawVisualization() {
// Create and populate the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('number', 'Height');
data.addRows(3);
data.setCell(0, 0, 'Tong Ning mu');
data.setCell(1, 0, 'Huang Ang fa');
data.setCell(2, 0, 'Teng nu');
data.setCell(0, 1, 174);
data.setCell(1, 1, 523);
data.setCell(2, 1, 86);
// Create and draw the visualizations.
new google.visualization.ColumnChart(document.getElementById('visualization1')).
draw(data, null);
new google.visualization.ColumnChart(document.getElementById('visualization2')).
draw(data, null);
}
google.setOnLoadCallback(drawVisualization);
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<cc1:TabContainer ID="TabContainer1" runat="server">
<cc1:TabPanel runat="server" HeaderText="TabPanel1" ID="TabPanel1">
<ContentTemplate>
<div id="visualization1" style="width: 300px; height: 300px;">
</div>
</ContentTemplate>
</cc1:TabPanel>
<cc1:TabPanel runat="server" HeaderText="TabPanel1" ID="TabPanel2">
<ContentTemplate>
<div id="visualization2" style="width: 300px; height: 300px;">
</div>
</ContentTemplate>
</cc1:TabPanel>
</cc1:TabContainer>
</div>
</form>
</body>
</html>
Ok, I didn't get a single response to this post so here is how I worked around the problem, hope it helps someone.
I never actually got the the root of this problem but I found that if I delayed the loading of the Visualisations till the tab that contains it is clicked then the problem goes away.
In the TabControl I call a JavaScript function to load the tabs visualisation when clicked:
<cc1:TabContainer ID="TabContainer1" runat="server" OnClientActiveTabChanged="tabChanged">
<cc1:TabPanel runat="server" HeaderText="TabPanel1" ID="TabPanel1">
<ContentTemplate>
<div id="visualization1" style="width: 300px; height: 300px;"></div>
</ContentTemplate>
</cc1:TabPanel>
<cc1:TabPanel runat="server" HeaderText="TabPanel1" ID="TabPanel2">
<ContentTemplate>
<div id="visualization2" style="width: 300px; height: 300px;"></div>
</ContentTemplate>
</cc1:TabPanel>
</cc1:TabContainer>
The JavaScript function
function tabChanged(sender, args) {
var ActiveTab = sender.get_activeTabIndex();
if (sender.get_activeTabIndex() == 0) {
if (tab0Loaded != true) {
//load the visualisation
new google.visualization.ColumnChart(document.getElementById('visualization2')).draw(data, null);
tab0Loaded = true
}
}
if (sender.get_activeTabIndex() == 1) {
if (tab1Loaded != true) {
//load the visualisation
new google.visualization.ColumnChart(document.getElementById('visualization2')).draw(data, null);
tab1Loaded = true
}
}
}
During postback the active tab could change, to cope with this I have a JavaScript function that executes when the page loads, if the current active tab is one containing a visualisation then I load it.