Run javascript function on loaded page - javascript

Very new to Javascript, so working on my first project. Attempting to run a script that gathers listing numbers, opens them in a URL and clicks an element on the loaded page. I can't get .click() to run on the resulting loaded page.
I've tried to set the logIn function to only run once the resulting page has loaded, but it doesn't seem to be doing the trick. AM I missing something basic?
var listingNum = prompt("Listing numbers").split(" ");
logIn = function(){
if(document.readyState === "complete"){
document.getElementById('SignInAsMemberLinkHeader').click();
}
};
for(i = 0; i < listingNum.length; i++){
window.open("http://www.website.com" + listingNum[i],"_self");
setInterval(logIn(), 4000);
};

Okay, the following test harness worked for me. I had to change your _self reference to _blank, so that each page loads separately and doesn't overwrite the operation of the parent page. You then just handle the load event of each window that is instantiated using window.open(). This was the part you were missing. You weren't handling the load events of the loaded windows.
You may wish to check that the SignInAsMemberLinkHeader element exists prior to calling click() on it, but I'll leave that up to you to implement.
NB this will not work if cross site scripting restrictions apply.
Hope this helps :)
<!DOCTYPE HTML>
<html>
<head>
<title>External Page Opener Test</title>
<meta charset="UTF-8">
<style>
body {
background-color:cornflowerblue;
color:white;
font-family:Tahoma,Arial,sans-serif;
}
</style>
<script>
window.addEventListener('load', init, false);
function init(event) {
var listings = prompt("Listing numbers:");
if (listings) {
var listingNum = listings.split(" ");
for (i = 0; i < listingNum.length; i++) {
// I used my local desktop and 3 test HTML files,
//each with a button click and handler on them.
var url = "file:///C:/Users/******/Desktop/" + listingNum[i];
var handle = window.open(url, "_blank");
handle.addEventListener('load', extPageLoaded, false);
}
} else {
console.log('No listings were entered.');
}
}
function extPageLoaded(event) {
const TIME_TO_WAIT_IN_MILLISECONDS = 4000;
setTimeout(
function() {
event.target.getElementById('SignInAsMemberLinkHeader').click();
},
TIME_TO_WAIT_IN_MILLISECONDS
);
}
</script>
</head>
<body>
</body>
</html>

Related

IE 11 onload is never called

My web page has following javascript
function LoadPDF(filename)
{
var loc = filename;
document.getElementById("pdf").setAttribute("src", loc);
if (window.addEventListener) {
document.getElementById("pdf").addEventListener("load", LoadPrint, false);
}
else if (window.attachEvent) {
document.getElementById("pdf").attachEvent("onload", LoadPrint);
}
else {
document.getElementById("pdf").onload = LoadPrint;
}
}
function LoadPrint() {
alert('fired!');
if (document.getElementById("pdf").src !== "") {
var frm = document.getElementById("pdf");
frm.contentDocument.getElementById("pdf").contentWindow.print();
}
}
The LoadPDF is called from code behind. "pdf" is my iframe. When the pdf is loaded into the iframe I want to call LoadPrint. But the trouble is in IE 11 its never called.
Can anyone please help?
This is an IE11 bug, which MS refuses to fix because they consider it a feature bug and they no longer fix that kind of bugs for old browser versions.
A workaround to this bug, is to load the pdf file inside an other page iframe and then load that page inside your iframe. A simple javascript pdf loader with a file argument:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>PDF Loader</title>
<style type="text/css">
html, body {
border:0;
margin:0;
height:100%;
overflow-y:hidden;
}
#pdf {
border:0;
margin:0;
width:100%;
height:100%;
}
</style>
</head>
<body>
<iframe id="pdf"></iframe>
<script type="text/javascript">
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
var pdf = getParameterByName('pdf');
document.getElementById('pdf').setAttribute('src', pdf);
</script>
</body>
</html>
You can use it with the <filename.html>?pdf=<pdf_file_to_load>.
Then you just change your code to load the pdf file through that loader like this:
function LoadPDF(filename)
{
var loc = "pdf-loader.html?pdf="+filename;
document.getElementById("pdf").setAttribute("src", loc);
if (window.addEventListener) {
document.getElementById("pdf").addEventListener("load", LoadPrint, false);
}
else if (window.attachEvent) {
document.getElementById("pdf").attachEvent("onload", LoadPrint);
}
else {
document.getElementById("pdf").onload = LoadPrint;
}
}
function LoadPrint() {
alert('fired!');
}
LoadPDF('http://www.pdf995.com/samples/pdf.pdf');
Now the LoadPrint function is called on iframe load event even on IE11.
Here is my working example you can even test with IE11: http://zikro.gr/dbg/html/ie11-iframe-pdf/
Here you can see a screen capture with the 10MB PDF loading and only after it finish loading it fires the load event and alerts the message:
I don't know if this is your specific issue in this instance, but make sure you bind your listeners to the element before you assign it's src attribute. If the item is in cache it is possible for the load event to fire before you bind to it, thus missing it entirely.

How can I inject JS and collect alert message from website?

I am trying to collect alert from website by using overwrite method. I searched on google and found wappalyzer, a Chrome/Firefox extension to detect software on website. It injects a script inject.js when page load and collect information. My method is similar. I make a local website and test it. When I inject overwrite_alert.js manually then it works.
But I want to do it dynamically and apply to other website. So I use headless browser like PhantomJS. The following code which I tried in PhantomJS but it does not work.
I am trying to inject a JavaScript on phantom JS. Like this code:
<!DOCTYPE html>
<html>
<head>
<title>Test alert</title>
<!-- !!! Inject here !!! <script src="overwrite_alert.js"></script> -->
<script type="text/javascript" src="other_script.js"> </script>
<script type="text/javascript">
alert("Alert content");
</script>
</head>
<body>
<h1>website content</h1>
</body>
</html>
overwrite_alert.js file from this question:
(function() {
var _alert = window.alert; // <-- Reference
window.alert = function(str) {
// do something additional
if(console) console.log(str);
//return _alert.apply(this, arguments); // <-- The universal method
_alert(str); // Suits for this case
};
})();
I tried with onLoadStarted event and My PhantomJS code:
var webPage = require('webpage');
var page = webPage.create();
var url = "https://localhost:5000/alert.html";
page.onConsoleMessage = function(msg, lineNum, sourceId) {
console.log('CONSOLE> ' + msg);
};
page.onLoadStarted = function() {
if (page.injectJs('do.js')) {
var title = page.evaluate(function() {
// returnTitle is a function loaded from our do.js file - see below
console.log("evaluate completed");
});
console.log(title);
}
}
page.open(url, function(status) {
if (status === "success") {
if (page.injectJs('do.js')) {
var title = page.evaluate(function() {
// returnTitle is a function loaded from our do.js file - see below
console.log("evaluate completed");
});
console.log(title);
phantom.exit();
}
page.render("onOpen.png");
}
});
Result:
$ phantomjs test_inject.js
CONSOLE> from onLoadStarted completed
null
CONSOLE> from page.open
null
Since the page.open callback is called after a page is loaded, it would be simply to late to change the implementation of window.alert. You would need to use earlier events such as page.onInitialized, page.onLoadStarted, etc.
Since you're interested in alerts, you don't need to do that at all, because PhantomJS provides an event for that: page.onAlert

Detect connection issues in iframe

this questions is related to an html file calling out different pages in different iframe tags. Is there a way, using JavaScript probably, to check if there was a connection issue to the page? If so, to try reloading this frame until the connection is established.
To be a bit clearer, if you have a look at the following link (http://tvgl.barzalou.com) (even if the content is in French, you will notice how different parts of the page load, and more often than not, loads correctly). But once in a while, during the weekend, a slight connection issue to the net arrives and for some reason, the frame gives out this ridiculous grey / light grey icon saying that there was a connection issue. Of course, when the page is manually reloaded, the frame comes back to life.
Please check the updated code that will check and reload the iframe after the max attempts have been reached...
<script language="javascript">
var attempts = 0;
var maxattempt = 10;
var intid=0;
$(function()
{
intid = setInterval(function()
{
$("iframe").each(function()
{
if(iframeHasContent($(this)))
{
//iframe has been successfully loaded
}
if(attempts < maxattempt)
{
attempts++;
}
else
{
clearInterval(intid);
checkAndReloadIFrames();
}
})
},1000);
})
function iframeHasContent($iframe)
{
if($iframe.contents().find("html body").children() > 0)
{
return true;
}
return false;
}
function checkAndReloadIFrames()
{
$("iframe").each(function()
{
//If the iframe is not loaded, reload the iframe by reapplying the current src attribute
if(!iframeHasContent($(this)))
{
//reload iframes if not loaded
var $iframe = $(this);
var src = $iframe.attr("src");
//code to prevent cache request and reload url
src += "?_" + new Date().getTime();
$iframe.attr("src",src);
}
});
}
</script>
You can schedule a code which will check whether the iframes are loaded properly or not
Consider a sample
<script language="javascript">
var attempts = 0;
var maxattempt = 10;
var intid=0;
$(function()
{
intid = setInterval(function()
{
$("iframe").each(function()
{
if(iframeHasContent($(this)))
{
//iframe has been successfully loaded
}
if(attempts < maxattempt)
{
attempts++;
}
else
{
clearInterval(intid);
}
})
},1000);
})
function iframeHasContent($iframe)
{
if($iframe.contents().find("html body").children() > 0)
{
return true;
}
return false;
}
</script>
This simple code snippet will check whether iframes in the document have been loaded properly or not. It will try this for 10 attempts then it will abort the checking.
When the checking is aborted, you can call iframeHasContent() for each iframe to shortlist the ones that have not been loaded and reload them if required.

Disable link after child window is open, restore once child window is closed

My client has a link on their website which opens a customer service chat window in a popup. They are seeing users clicking the chat link multiple times, which opens multiple chat sessions, and it is throwing off their stats. I need to disable the link when the chat window is opened, and restore it when the chat window has been closed. I can't modify/access child window.
The original link looks like this:
<a class="initChat" onclick="window.open('https://chatlinkhere.com','chatwindow','width=612,height=380,scrollbars=0'); return false;">
I figured the best thing to do would be to store the window.open() as a variable in a function:
function openChat() {
child = window.open('http://www.google.com', 'chatwindow', 'width=612,height=380,scrollbars=0,menubar=0');
}
and change the link HTML to
<a class="initChat" onclick="openChat();">
Note: Ideally, I'd like to detect the original onclick's value, and store it in a variable. Something like:
jQuery('.initChat').find().attr('onclick');
But I'm not sure how to store it and then call it later.
Next I need to run a check to see if the chat window is open or not:
timer = setInterval(checkChild, 500);
function checkChild() {
if (child.open) {
alert("opened");
jQuery(".initChat").removeAttr("onclick");
jQuery(".initChat").css("opacity", ".5");
clearInterval(timer);
}
if (child.closed) {
alert("closed");
jQuery(".initChat").attr('onclick', 'openChat(); checkChild();');
jQuery(".initChat").css("opacity", "1.0");
clearInterval(timer);
}
}
Note: the alerts are just there for testing.
And add the new function to the link
<a class="initChat" onclick="openChat(); checkChild();">
And once the chat window is closed, I need to restore the onclick attribute to the link (is there an easier way to do this?)
Fiddle demo is here -> http://jsfiddle.net/JkthJ/
When I check Chrome Console I'm getting error
Uncaught TypeError: Cannot read property 'open' of undefined
UPDATE
Whoever left me the answer in http://jsfiddle.net/JkthJ/2/ thank you very much it works! :)
i think you need is open pop up if already open then foucus on pop up or noyhing should happen
you can rewrite your function as
var winPop = false;
function OpenWindow(url){
if(winPop && !winPop.closed){ //checks to see if window is open
winPop.focus(); // or nothing
}
else{
winPop = window.open(url,"winPop");
}
}
just do it in a simple way. disable the mouse events on anchor link after child window open.
css
.disableEvents{
pointer-events: none;
}
js
var childWindow;
$('a').on('click',function(){
childWindow = window.open('_blank',"height:200","width:500");
$(this).addClass('disableEvents');
});
if (typeof childWindow.attachEvent != "undefined") {
childWindow.attachEvent("onunload", enableEvents);
} else if (typeof childWindow.addEventListener != "undefined") {
childWindow.addEventListener("unload", enableEvents, false);
}
enableEvents = function(){
$('a').removeClass('disableEvents');
};
update
your child window is plain html page. Do the changes in child window html code:
<html>
<head>
<script>
function myFunction()
{
window.opener.enableEvents(); //it calls enableEvents function
}
</script>
</head>
<body onunload="myFunction()">
<!--your content-->
</body>
</html>
This is what I got to finally work:
<a class="initChat" onclick="checkWin()"></a>
<script>
var myWindow;
function openWin() {
myWindow = window.open('https://www.google.com', 'chatwindow', 'width=612,height=380,scrollbars=0');
}
function checkWin() {
if (!myWindow) {
openWin();
} else {
if (myWindow.closed) {
openWin();
} else {
alert('Chat is already opened.');
myWindow.focus();
}
}
}
</script>

'pageshow' is not received when pressing "back" button on Safari on *IPad"

I have the following handler:
$(window).bind('pageshow', function() { alert("back to page"); });
When I navigate away from the page (by pressing on a link) and return back to the page (by pressing the "back" button), the alert() is not called (IPad 2, iOS 5.1).
What am I doing wrong please? Any other event I need to bind to?
PS: interesting that pagehide is received properly when navigating away from the page.
You can check the persisted property of the pageshow event. It is set to false on initial page load. When page is loaded from cache it is set to true.
window.onpageshow = function(event) {
if (event.persisted) {
alert("back to page");
}
};
For some reason jQuery does not have this property in the event. You can find it from original event though.
$(window).bind("pageshow", function(event) {
if (event.originalEvent.persisted) {
alert("back to page");
}
};
This is likely a caching issue. When you go back to the page via the "back" button, the page is being pulled from the cache (behavior is dependent on the browser). Because of this, your JS will not fire since the page is already rendered in the cache and re-running your js could be detrimental to layout and such.
You should be able to overcome this by tweaking your caching headers in your response or using a handful of browser tricks.
Here are some links on the issue:
Is there a cross-browser onload event when clicking the back button?
After travelling back in Firefox history, JavaScript won't run
EDIT
These are all pulled from the above links:
history.navigationMode = 'compatible';
<body onunload=""><!-- This does the trick -->
"Firefox 1.5+ and some next version of Safari (which contains the fix for bug 28758) supports special events called pageshow and pagehide."
Using jQuery's $(document).ready(handler)
window.onunload = function(){};
What you're doing there is binding the return value of alert("back to page") as a callback. That won't work. You need to bind a function instead:
$(window).bind('pageshow', function() { alert("back to page"); });
I add the same problem where iOS does not always post the "pageshow" event when going back.
If not, safari resumes executing JS on the page so I though a timer would continue to fire.
So I came with this solution:
var timer;
function onPageBack() { alert("back to page"); }
window.addEventListener('pageshow', function() {
if (event.persisted)
onPageBack();
// avoid calling onPageBack twice if 'pageshow' event has been fired...
if (timer)
clearInterval(timer);
});
// when page is hidden, start timer that will fire when going back to the page...
window.addEventListener('pagehide', function() {
timer = setInterval(function() {
clearInterval(timer);
onPageBack();
}, 100);
});
I solved that issue like that;
$(window).bind("pageshow", function () {
setTimeout(function () {
back();
}, 1000);
});
function back() {
//YOUR CODES
}
you should checkout you page is has iFrame component? i dont know why , but i delete iFrame component to solve this question
The only way I got this to work across ALL web browsers is to disallow the caching of the page you are returning to. I know -- it is a bit radical; it would be nice to get it to work using JavaScript, but I could figure it out.
I added a Cache-Control header in my .asp pages a helpful list of most options available to add the header..
My test.asp page
<%#language="VBSCRIPT" CODEPAGE="65001" LCID=1033%>
<%
Option Explicit
SetLocale(1033)
Response.ContentType = "text/html"
Response.CharSet = "UTF-8"
Response.addHeader "Cache-Control", "no-cache, no-store, must-revalidate" ' HTTP 1.1.
Response.addHeader "Pragma", "no-cache" ' HTTP 1.0.
Response.addHeader "Expires", "0" ' Proxies.
%><html>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
<style>
body {margin: 50px auto;text-align: center;}
a {padding: 5px;}
#spinner {width: 100%;height: 100%;background: green;position: absolute;top: 0;display:none;}
</style>
<head>
</head>
<body style="min-height: 100vh;">
Hello World!<br>
<h3 id="pagevalue"></h3>
page 1
page 2
page 3
<div id="spinner"></div>
<script>
function showSpinner(){
document.getElementById("spinner").style.display = "block";
}
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = window.location.search.substring(1),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
}
}
return false;
};
document.getElementById("pagevalue").innerHTML = "page "+getUrlParameter("page");
</script>
</body>
</html>
To complete your
alert("back to page")
request, I suggest you add a tracking mechanism that keeps track of the clicks.

Categories