Using a simple javascript snippet on google chrome, I am attempting to navigate to various webpages and downloading select files from them.
Here is my code so far..
var thumbnails= document.getElementsByClassName('mythumbnails')
var arr=Array.prototype.slice.call(thumbnails)
timeToCloseWindow=10000;
function work() {
if(thumbnails.length==0) return;
var url = arr.shift();
var openWindow = window.open(url.href);
setTimeout(function () {
document.getElementsByClassName("download-icon")[0].click()
openWindow.close();
work();
}, timeToCloseWindow);
}
work()
Unfortunately, I run into the error Cannot read property 'click' of undefined. I have also tried using a for loop with a sleep condition with the same error. Any idea what I am doing wrong?
window.location = url.href;
document.getElementsByClassName("download-icon")[0].click()
Related
I want to automate clicking the agree button to Google's cookie policies.
(I clean cookies after closing a tab, and I don't want to create a google account, so I get asked every time I use google)
There is a div element with the ID "introAgreeButton" that I'm trying to access with my script:
<div role="button" id="introAgreeButton" [...]></div>
However, document.getElementById('introAgreeButton') always returns null.
My first thought was that the element wasn't loaded by the time my function was executed. But it doesn't work if I execute it on window.onload, or even if I run it in a loop until the element is definitely there:
window.onload = function() {
var x = document.getElementById('introAgreeButton')
console.log(x)
}
Output:
null
function loop() {
var x = document.getElementById('introAgreeButton')
if (x) {
console.log('success')
} else {
loop()
}
}
Output:
null
null
null
...
Can be tested on https://www.google.com/search?hl=en&q=test
Anyone have an idea why this is and how to solve it?
Edit: I execute the script via the browser extension TamperMonkey
You can use setInterval to check if element is rendered in DOM like this :
document.addEventListener('DOMContentLoaded', function () {
var intervalID = null;
function checkElementInDOM () {
var element = document.getElementById('introAgreeButton');
if (element) {
clearInterval(intervalID);
// DO YOUR STUFF HERE ...
}
}
intervalID = setInterval(checkElementInDOM, 100);
});
To be used intelligently, however, so as not to have a setInterval which works continuously. Maybe think about adding a maximum number of attempts.
Problem: I have a asp.net button and on click of that I am displaying another window using window.open() at the client side using <script></script>
"I actually, need a popup (alert message) to be displayed on my parent page where my button is located once the user closes the child window."
Couple of things I tried are as follows:
I tried using setTimeOut() to have a time out for some milliseconds. This does not work as the control is not waiting until the time out is complete. It just proceeds to execute next set of code.
I tried using setInterval() but for some reason it is not working for me. Below is the code snippet of that:
$(document).ready(function () {
$('#<%=btnClick.ClientID%>').bind('click', function () {
var newWindow = window.open("http://www.google.com/", "google", 'resizable=1,width=900,height=800,scrollbars=1', '_blank');
newWindow.moveTo(0, 0);
var test = setInterval(function (e) {
if (newWindow.closed) {
alert("HEYY");
clearInterval(test);
__doPostBack("<%= btnClick.UniqueID %>", "");
}
else {
e.preventDefault();
}
}, 5000);
});
});
.
I also tried making an ajax call to open the new window and make it async : false, it again did not help me.
Bring your window and timer variable out of scope of the event handler. You need to do a polling i.e. periodically keep on checking if the windows has been closed. Using setInterval to do a polling will do the job.
var newWin, pollTimer;
$('#btnId').bind('click', function () {
newWin = window.open("...", "...", "");
pollTimer = window.setInterval(function() {
if (newWin.closed) {
window.clearInterval(pollTimer);
callCodeWhenPopupCloses();
}
}, 5000);
});
function callCodeWhenPopupCloses() {
alert("Popup closed.");
...
}
First Question here, too! Yay! Just moved this from AskUbuntu.
I am just about to finish a little private project for gaining some experience where i try to change the app layout so it works as a normal website (on Jimdo, so it was quite of a challenge first) without much JavaScript required but is fully functional on mobile view.
Since Jimdo serves naturally only the actual site, I had to implement an
if (activeTab.getAttribute('jimdo-target') != null)
location.href = activeTab.getAttribute('jimdo-target');
redirect into the __doSelectTab() function in tabs.js . (In js I took the values from the jimdo menu string to build the TABS menu with this link attribute)
Now everything works fine exept at page load the first tab is selected. I got it to set the .active and .inactive classes right easily, but it is not shifted to the left.
So my next idea is to let it initialize as always and then send a command to change to the current tab.
Do you have any idea how to manage this? I couldn't because of the this.thisandthat element I apparently don't really understand...
Most of you answering have the toolkit and the whole code, but I am listing the select function part of the tabs.js:
__doSelectTab: function(tabElement, forcedSelection) {
if ( ! tabElement)
return;
if (tabElement.getAttribute("data-role") !== 'tabitem')
return;
if (forcedSelection ||
(Array.prototype.slice.call(tabElement.classList)).indexOf('inactive') > -1) {
window.clearTimeout(t2);
activeTab = this._tabs.querySelector('[data-role="tabitem"].active');
offsetX = this.offsetLeft;
this._tabs.style['-webkit-transition-duration'] = '.3s';
this._tabs.style.webkitTransform = 'translate3d(-' + offsetX + 'px,0,0)';
this.__updateActiveTab(tabElement, activeTab);
if (activeTab.getAttribute('jimdo-target') != null)
location.href = activeTab.getAttribute('jimdo-target');
[].forEach.call(this._tabs.querySelectorAll('[data-role="tabitem"]:not(.active)'), function (e) {
e.classList.remove('inactive');
});
var targetPageId = tabElement.getAttribute('data-page');
this.activate(targetPageId);
this.__dispatchTabChangedEvent(targetPageId);
} else {
[].forEach.call(this._tabs.querySelectorAll('[data-role="tabitem"]:not(.active)'), function (el) {
el.classList.toggle('inactive');
});
var self = this;
t2 = window.setTimeout(function () {
var nonActiveTabs = self._tabs.querySelectorAll('[data-role="tabitem"]:not(.active)');
[].forEach.call(nonActiveTabs, function (el) {
el.classList.toggle('inactive');
});
}, 3000);
}
},
...and my app.js hasn't anything special:
var UI = new UbuntuUI();
document.addEventListener('deviceready', function() { console.log('device ready') }, true);
$(document).ready(function () {
recreate_jimdo_nav();
UI.init();
});
So meanwhile found a simple workaround, however I'd still like to know if there is another way. Eventually I noticed the __doSelectTab() function is the one that executes the click, so it does nothing but to show the other tab names when they are hidden first. so I added the global value
var jnavinitialized = false;
at the beginning of the tabs.js and run
var t = this;
setTimeout(function(){t.__doSelectTab(t._tabs.querySelector('[data-role="tabitem"].jnav-current'))}, 0);
setTimeout(function(){t.__doSelectTab(t._tabs.querySelector('[data-role="tabitem"].jnav-current'))}, 1);
setTimeout(function(){jnavinitialized = true;}, 10);
at the top of the __setupInitialTabVisibility() function. Then I changed the location.href command to
if (activeTab.getAttribute('jimdo-target') != null && jnavinitialized)
location.href = activeTab.getAttribute('jimdo-target');
And it works. But originally I searched for a way to change the tab on command, not to run the command for selecting twice. So if you know a better or cleaner way, you are welcome!
I am using the folowing script to check if device is online or offline:
function checkConnection() {
document.addEventListener("online", onDeviceOnline, false);
document.addEventListener("offline",onDeviceOffline, false);
function onDeviceOnline(){
loadZive();
loadMobil();
loadAuto();
};
function onDeviceOffline(){
alert("deviceIsOffline");
};
};
checkConnection();
Then I have this function to load feed:
function loadZive(publishedDateConverted){
google.load("feeds", "1");
function initialize() {
var feed = new google.feeds.Feed("http://www.zive.sk/rss/sc-47/default.aspx");
feed.setNumEntries(window.localStorage.getItem("entriesNumber"));
feed.load(function(result) {
if (!result.error) {
var feedlist = document.getElementById("feedZive");
for (var i = 0; i < result.feed.entries.length; i++) {
var li = document.createElement("li");
var entry = result.feed.entries[i];
var A = document.createElement("A");
var descriptionSettings = window.localStorage.getItem("descriptionSettings");
if (descriptionSettings=="true"){
var h3 = document.createElement("h3");
var p = document.createElement("p");
var pDate = document.createElement("p");
pDate.setAttribute("style","text-align: right; margin-top: 5px;");
var publishedDate = new Date(entry.publishedDate);
publishedDateConverted = convertTime(publishedDate);
pDate.appendChild(document.createTextNode(publishedDateConverted));
h3.setAttribute("style","white-space: normal;")
h3.appendChild(document.createTextNode(entry.title));
p.setAttribute("style","white-space: normal;")
p.appendChild(document.createTextNode(entry.content));
A.setAttribute("href",entry.link);
A.appendChild(h3);
A.appendChild(p);
A.appendChild(pDate);
}
else{
A.setAttribute("href",entry.link);
A.setAttribute("style","white-space: normal;")
A.appendChild(document.createTextNode(entry.title));
};
li.appendChild(A);
feedlist.appendChild(li);
}
$("#feedZive").listview("refresh");
}
});
}
google.setOnLoadCallback(initialize);
};
First I load second script, then first. But I cant see anything. If I turn my app on then I see page layout for abou 1 sec then (probably after loading first script) function onDeviceOnline() happens and I can see only blank page. But it should load feeds into existing template.
IMHO onDeviceOnline function happens after loading the page template and therefore it cant import feeds. If I create function like this:
function loadFeeds(){
loadZive();
loadMobil();
loadAuto();
};
then everything works fine so I think it has something to do with online and offline eventlisteners. It also didnt work when I put checkconnection into onDeviceReady function so it should not be the problem. So is there any way to check if device is online and if it is then use js file to load feeds?
EDIT: I have used Simon McDonald suggestion and created code like this:
function onDeviceReady(){
document.addEventListener("backbutton", onBackKeyDown, false);
function onBackKeyDown(){
navigator.app.exitApp();
}
function checkConnection() {
var networkState = navigator.network.connection.type;
if (networkState == "none"){
alert("no network connection");
}
else{
loadZive();
loadMobil();
loadAuto();
};
};
checkConnection();
};
With this code alerts are working perfectly for device online and device offline but when I try to loadFeed I get the same result as before (page layout loads and then everything changes to blank page).
The problem is that you are adding a "online" event listener in device ready event listener but the device is already on line so the event will not fire again until there is a change in connectivity. In your device ready event listener you should check the value of navigator.connection.network.type and make sure it isn't NONE.
http://docs.phonegap.com/en/2.0.0/cordova_connection_connection.md.html#connection.type
For a class project i am trying to count the number of clicks a button gets, save the search term, and then open a new html file. my problem is that the "doCoolThings" function will not call the "newWindow" function. I cannot figure out how to get the newWindow function to execute after i click submit.
here is my code:
window.onload = init;
function init() {
var myButton = document.getElementById("submitButton");
myButton.onclick = doCoolThings;
}
function doCoolThings(){
alert("test count");
localStorage.searchTerms = document.getElementById("searchWord").value;
//var searchOutput = document.getElementById("searchOutput");
searchWord.innerHTML = searchTerms;
if (localStorage.clickcount)
{
localStorage.clickcount=Number(localStorage.clickcount)+1;
//window.open("scroogleresults.html");
}
else
{
localStorage.clickcount=1;
//window.location="scroogleresults.html";
}
var myCounter = document.getElementById("numberClicks");
var counter = localStorage.clickcount;
myCounter.innerHTML = counter;
newWindow();
}
function newWindow(){
alert("new window");
window.open("scroogleresults.html");
}
If this is the extent of your code, it looks to me like you have some javascript errors. You should be checking the error console or debug console in your browser for javascript errors that cause your scripts to abort. Here are a couple errors I see:
Error #1
In doCoolThings(), when you do this:
searchWord.innerHTML = searchTerms;
I don't see any place that searchTerms is defined so this would generate a script error.
Error #2
You should be using getItem() and setItem() to access localStorage.