I`m trying to create two banners with adobeEdge and import them with iframes within 3rd file. So the structure would be something like this:
banner1.html
banner2.html
index.html (where banner1 and banner2 will be embed via iframe).
Those two banners will be animated, however file size, loading time of each may vary so they will not be loaded in the same time.
The problem is that I need them both to start playing in exact same time (in flash that is called local connection), so the idea is to check when both iframes are loaded and if each of them send DONE message to the other one I will play them.
I wrote a code which actually work, but still one banner always has a delay. Here is my code:
Banner 1
<script type="text/javascript">
var fr = window.parent.frames["frame2"];
var frwin = fr.contentWindow;
var otherLoaded = false;
var selfLoaded = false;
var process = setInterval(function(){load();},10);
window.addEventListener("message", receiveMessage, false);
function setLoaded(){
selfLoaded = true;
frwin.postMessage("Done", "DOMAIN");
}
function load(){
if(otherLoaded === true && selfLoaded === true){
clearInterval(process);
AdobeEdge.bootstrapCallback(function(compId) {
AdobeEdge.getComposition(compId).getStage().play();
});
}else if(selfLoaded === true && otherLoaded !== true){
frwin.postMessage("resend", "http://izorgor.com");
}
}
function receiveMessage(event) {
if (event.origin !== "DOMAIN")
return;
if(event.data === 'Done'){
otherLoaded = true;
console.log("Done");
}
if(event.data === 'resend'){
fr = window.parent.frames["frame2"];
frwin = fr.contentWindow;
frwin.postMessage("Done", "DOMAIN");
console.log("resend");
}
}
</script>
Banner 2
<script type="text/javascript">
var fr = window.parent.frames["frame1"];
var frwin = fr.contentWindow;
var otherLoaded = false;
var selfLoaded = false;
var process = setInterval(function(){load();},10);
window.addEventListener("message", receiveMessage, false);
function setLoaded(){
selfLoaded = true;
frwin.postMessage("Done", "DOMAIN");
}
function load(){
if(otherLoaded === true && selfLoaded === true){
clearInterval(process);
AdobeEdge.bootstrapCallback(function(compId) {
AdobeEdge.getComposition(compId).getStage().play();
});
}else if(selfLoaded === true && otherLoaded !== true){
frwin.postMessage("resend", "http://izorgor.com");
}
}
function receiveMessage(event) {
if (event.origin !== "DOMAIN")
return;
if(event.data === 'Done'){
otherLoaded = true;
console.log("Done");
}
if(event.data === 'resend'){
fr = window.parent.frames["frame1"];
frwin = fr.contentWindow;
frwin.postMessage("Done", "DOMAIN");
console.log("resend");
}
}
</script>
index.html
<iframe width="900" height="200" id="frame1" src="banner1.html" frameborder="0" scrolling="no"></iframe>
Thanks
I think you should contact your AdServer and ask if they are serving the Ad in just one TAG or in two TAGs
You can use libraries as https://github.com/jeremyharris/LocalConnection.js/tree/master
(similar to Flash Local Connection)
You can simply communicate between all your iframes in a window with a JavaScript library that I developed.
Get Documentation or Fork on GitHub. It uses nativ DOM to connect iframes with each other.
Sample usage :
include first LocalConnection script to all your banner. In this sample code we assume there are 2 banners need to communicate with each other. But it works also any number of banners.
in first banner :
<script>
LC.key = 'uniqueConnectionString';
LC.name = 'right'; // desc: my name is right and
LC.frames = 'left'; // I want to connect to the banner called left
LC.onConnect = function () {
console.log('Do this as soon as connection established!');
/*
From this point window of left and top will be available as
LC.left and LC.top
for example :
*/
LC.left.document.getElementsByTagName('body')[0].style.backgroundColor = 'pink';
};
</script>
On the second banner put the same code but change name and frames values like this :
<script>
LC.key = 'uniqueConnectionString';
LC.name = 'left'; // desc: my name is left and
LC.frames = 'right'; // I want to connect to the banner called right
LC.onConnect = function () {
console.log('Do this as soon as connection established!');
/*
From this point window of left and top will be available as
LC.left and LC.top
for example :
*/
LC.left.document.getElementsByTagName('body')[0].style.backgroundColor = 'pink';
};
LC.connect();
</script>
Related
I'm having trouble with prefers-color-scheme with the logic that I'm trying to achieve. For example, with the prefers-color-scheme I have a toggle on my site that overrides this is a user prefers black while using light mode, and vice versa. The issue I'm running into is I can't toggle it so that when a user changes the toggle to set it to the OS color theme, when they switch pages the theme switches back to the prefers color scheme. I already have local storage setup and variables called theme type and on.
When I comment out the detect color scheme function, the local storage remembers the users desired theme setting. When uncommented it overrides and always picks the theme os color scheme. How can I get my logic working right where when on the users first entry point before the local storage is created that it reads the theme OS but if the user changes the theme to black and vice versa that the OS doesn't override when on page change?
Thanks.
So the detectColorScheme checks users OS theme.
function detectColorScheme(){
var on = 1;
on = 1;
if (window.matchMedia('(prefers-color-scheme: dark)').matches && on <= 1) {
if (on = 1 ) {
on = 2;
darkmode();
console.log("OS Setting DARK MODE");
}
}
if (window.matchMedia("(prefers-color-scheme: light)").matches ) {
if (on = 1) {
lightmode();
console.log("OS Setting LIGHT MODE");
}
}
}
Then at the start of the javascript file I do the following :
document.body.style.backgroundColor = "";
if (localStorage.themepref == 1 ) {
detectColorScheme();
document.body.style.backgroundColor = "#FFF";
lightmode();
}
else {
detectColorScheme();
document.body.style.backgroundColor = "#0a0a0a";
darkmode();
localStorage.themepref = 2;
}
window.onload = function() {
console.log('First');
if (event.target.readyState === 'loading') {
detectColorScheme();
$('body').css({ background: ''});
document.body.style.backgroundColor = "inherit";
if(lightmodeON == true) {
detectColorScheme();
$('body').css({background: "#fbfcfd"});
document.body.style.backgroundColor = "#FFF";
}
if(lightmodeON == false) {
detectColorScheme();
$('body').css({background: "#0a0a0a"});
document.body.style.backgroundColor = "#0a0a0a";
}
}
};
And lastly
document.addEventListener("DOMContentLoaded", function() {
window.scrollTo(0, 0);
$(window).scrollTop( $("#top").offset().top );
$(document).scrollTop(0);
document.body.style.backgroundColor = "";
if (document.readyState === 'complete') {
if(lightmodeON == true) {
$('body').css({background: "#fbfcfd"});
console.log('loading white bg');
}
if(lightmodeON == false) {
$('body').css({background: "#0a0a0a"});
console.log('loading black bg');
}
}
if (typeof (Storage) !=="undefined") {
if (localStorage.themepref == 1 ) {
lightmode();
}
else {
darkmode();
localStorage.themepref = 2;
}
if(lightmodeON == true) {
$('body').css({background: "#fbfcfd"});
console.log('loading fffwhite bg');
}
if(lightmodeON == false) {
$('body').css({background: "#0a0a0a"});
console.log('loading black bg');
}
}
I have done this small effort, What I am doing is:
When user will load the website for first time, localStorage will be empty so we will setup the theme according to OS but then if user plays with our toggle, which if on then lightmode otherwise darkmode, then we will also save this in localstorage and next time when ever user will visit our page, we will check it's preference from the local storage, will never go back to OS theme.
Please have a look and let me know if it is any helpful. It will not work here as localStorage will not be supported here. Please copy and test in your browser.
<html lang="en">
<head>
<meta charset="utf-8">
<title>test</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<label style="color:yellow;">IsLightMode: </label>
<input id="toggleCheck" type="checkBox" onclick="toggle()" />
<script>
var lightmodeOn = true;
function changeColorOfBackground(lightmodeOn) {
if(lightmodeOn == true) {
// you can call your lightmode function here if want to set other things too.
$('body').css({background: "#fbfcfd"});
console.log('loading white bg');
}
if(lightmodeOn == false) {
// you can call your darkmode function here if want to set other things too.
$('body').css({background: "#0a0a0a"});
console.log('loading black bg');
}
}
function toggle() {
lightmodeOn = !lightmodeOn;
changeColorOfBackground(lightmodeOn);
localStorage.themepref = lightmodeOn?1:2;
}
document.addEventListener("DOMContentLoaded", function() {
//if it is not set in localStorage only then check OS theme otherwise always load from localStorage
if(localStorage.themepref === null) {
//if windows is light, then we should go with dark theme
if (window.matchMedia('(prefers-color-scheme: light)').matches) {
lightmodeOn = false;
}
}
else if (localStorage.themepref == 2 ) {
lightmodeOn = false;
}
if(lightmodeOn) {
$('#toggleCheck').prop('checked',true);
}
changeColorOfBackground(lightmodeOn);
});
</script>
</body>
</html>
I am trying to set up a tiny script for Firefox that runs in a javascript add-on (Greasemonkey). We have a queue that we monitor for arriving tickets, I coded something that is supposed to refresh the page every 2 minutes and do the following:
if tickets are found by this condition
if (isEmpty($('#incident_table > tbody'))&isEmpty($('#task_table > tbody')))
then I want the following to happen:
- task-bar blinks with a message so it is visible
- if the window is focused it will display "Tickets in the queue!" alert right away
- if the window is not focused, it will wait for 10 seconds, if still not focused - display "Tickets in the queue!" alert and bring the window to front.
I've got the refresh and blinking part, but I cannot get the focus part to work... I've been looking around and I see that Firefox is having some "issues" with window.focus() and all the "bring to front", most of the code below is inspired by stuff I've found on this site.
Any input is appreciated! I am also opened to alternatives - in the end, what this needs to do is refresh, check the condition and notify if I am already looking at it or if it is not focused wait 10 seconds with a "soft notify" (blink) then bring it to the front if I don't notice it.
Regards,
Dan
{
newExcitingAlerts = (function () {
var oldTitle = document.title;
var msg = "***NEW***";
var timeoutId;
var blink = function() { document.title = document.title == msg ? 'Tickets in queue!' : msg; };
var clear = function() {
clearInterval(timeoutId);
document.title = oldTitle;
window.onmousemove = null;
timeoutId = null;
};
return function () {
if (!timeoutId) {
timeoutId = setInterval(blink, 1000);
window.onmousemove = clear;
}
};
}());
$(document).ready(function(){
function isEmpty( el ){
return !$.trim(el.html());
}
if (isEmpty($('#incident_table > tbody'))&isEmpty($('#task_table > tbody'))) {
}
else{
newExcitingAlerts();
}
setTimeout(function() {
location.reload();
}, 120000);
});
}
Here is the alternative I've used, works like a charm. Web API notifications.
document.addEventListener('DOMContentLoaded', function () {
if (Notification.permission !== "granted")
Notification.requestPermission();
});
function notifyMe() {
if (!Notification) {
alert('Desktop notifications not available in your browser. Try Chromium.');
return;
}
if (Notification.permission !== "granted")
Notification.requestPermission();
else {
var notification = new Notification('Tickets in queue!', {
icon: 'http://siliconangle.com/files/2014/05/servicenow-icon.png',
body: "There are new tickets in queue, please acknowledge!",
});
notification.onclick = function () {
window.open("https://cchprod.service-now.com/task_list.do?sysparm_query=assignment_group%3D3139519437b7f1009654261953990e1f^ORassignment_group%3D31de85e337818a00ef8898a543990e99^ORassignment_group%3Da40029e937ec420065aa261953990eb5^ORassignment_group%3De903ad2d37ec420065aa261953990ecb^ORassignment_group%3Dd25fe5323779c24065aa261953990e54^ORassignment_group%3D508639363779c24065aa261953990e29^ORassignment_group%3D51fe5a37379e0a00ef8898a543990ea2^ORassignment_group%3D3d8171b23779c24065aa261953990e21^ORassignment_group%3Decfe5a37379e0a00ef8898a543990e6c^ORassignment_group%3D48c0b9723779c24065aa261953990e5d^ORassignment_group%3De5fde9fe3739c24065aa261953990e75^ORassignment_group%3D15fe5a37379e0a00ef8898a543990e99^ORassignment_group%3D15fe5a37379e0a00ef8898a543990ea7^ORassignment_group%3D1ed3f1f23779c24065aa261953990e47^active%3Dtrue^sys_class_name%3Dincident^ORsys_class_name%3Dsc_req_item^assigned_toISEMPTY&sysparm_first_row=1&sysparm_view=");
};
}
}
{
newExcitingAlerts = (function () {
var oldTitle = document.title;
var msg = "***NEW***";
var timeoutId;
var blink = function() {
document.title = document.title == msg ? 'Tickets in queue!' : msg;
};
var clear = function() {
clearInterval(timeoutId);
document.title = oldTitle;
window.onmousemove = null;
timeoutId = null;
};
return function () {
if (!timeoutId) {
timeoutId = setInterval(blink, 1000);
window.onmousemove = clear;
}
};
}
());
$(document).ready(function () {
function isEmpty(el) {
return !$.trim(el.html());
}
var x = document.getElementById("task_table").getAttribute("grand_total_rows");
if( x != "0" ) {
newExcitingAlerts();
notifyMe();
}
else
{
}
setTimeout(function() {
location.reload();
}
, 120000);
});
}
In Windows operating system you cannot focus the window while the window of another process is focused. You have to use js-ctypes to get around this.
On Mac OS X and Linux, I'm not sure if you can make your process steal focus from another with the normal functions. But if you can't you can for sure use js-ctypes to get the job done.
Here is how to do it in Windows - https://stackoverflow.com/a/32038880/1828637
It is harder on Windows then on OS X and Linux. I have focused windows on all systems using js-ctypes. So if you can't find out how to do with the functions available to you, let me know.
I'm attempting to load some images dynamically via .on('load') - via the following script:
.on('load', function() {
if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
alert('broken image!');
} else {
$("#rateholder").append(img);
}
});
Sometimes, however, the attempt fails for some reason or other. I'd like to put a timeout on it so if the image hasn't loaded within say...10 seconds...it runs a different function.
How would I append a timeout to this?
You can create a function that checks your image exists every 10 seconds.
Then do what you need if it doesn't.
var oneSecond = 1000;
var checkExist = setInterval(function() {
if ($('#the-image').length) {
console.log("Exists!");
clearInterval(checkExist);
}
else{
console.log('Does not Exist');
clearInterval(checkExist);
}
}, oneSecond*10);
I want to check with JavaScript if the user has already opened my website in another tab in their browser.
It seems I cannot do that with pagevisibility...
The only way I see is to use WebSocket based on a session cookie, and check if the client has more than one socket. But by this way, from current tab, I have to ask my server if this user has a tab opened right next to their current browser tab. It is a little far-fetched!
Maybe with localstorage?
The shorter version with localStorage and Storage listener
<script type="text/javascript">
// Broadcast that you're opening a page.
localStorage.openpages = Date.now();
var onLocalStorageEvent = function(e){
if(e.key == "openpages"){
// Listen if anybody else is opening the same page!
localStorage.page_available = Date.now();
}
if(e.key == "page_available"){
alert("One more page already open");
}
};
window.addEventListener('storage', onLocalStorageEvent, false);
</script>
Update:
Works on page crash as well.
Stimulate page crash in chrome: chrome://inducebrowsercrashforrealz
Live demo
Using local storage I created a simple demo that should accomplish what your looking to do. Basically, it simply maintains a count of currently opened windows. When the window is closed the unload events fire and remove it from the total window count.
When you first look at it, you may think there's more going on than there really is. Most of it was a shotty attempt to add logic into who was the "main" window, and who should take over as the "main" window as you closed children. (Hence the setTimeout calls to recheck if it should be promoted to a main window) After some head scratching, I decided it would take too much time to implement and was outside the scope of this question. However, if you have two windows open (Main, and Child) and you close the Main, the child will be promoted to a main.
For the most part you should be able to get the general idea of whats going on and use it for your own implementation.
See it all in action here:
http://jsbin.com/mipanuro/1/edit
Oh yeah, to actually see it in action... Open the link in multiple windows. :)
Update:
I've made the necessary changes to have the the local storage maintain the "main" window. As you close tabs child windows can then become promoted to a main window. There are two ways to control the "main" window state through a parameter passed to the constructor of WindowStateManager. This implementation is much nicer than my previous attempt.
JavaScript:
// noprotect
var statusWindow = document.getElementById('status');
(function (win)
{
//Private variables
var _LOCALSTORAGE_KEY = 'WINDOW_VALIDATION';
var RECHECK_WINDOW_DELAY_MS = 100;
var _initialized = false;
var _isMainWindow = false;
var _unloaded = false;
var _windowArray;
var _windowId;
var _isNewWindowPromotedToMain = false;
var _onWindowUpdated;
function WindowStateManager(isNewWindowPromotedToMain, onWindowUpdated)
{
//this.resetWindows();
_onWindowUpdated = onWindowUpdated;
_isNewWindowPromotedToMain = isNewWindowPromotedToMain;
_windowId = Date.now().toString();
bindUnload();
determineWindowState.call(this);
_initialized = true;
_onWindowUpdated.call(this);
}
//Determine the state of the window
//If its a main or child window
function determineWindowState()
{
var self = this;
var _previousState = _isMainWindow;
_windowArray = localStorage.getItem(_LOCALSTORAGE_KEY);
if (_windowArray === null || _windowArray === "NaN")
{
_windowArray = [];
}
else
{
_windowArray = JSON.parse(_windowArray);
}
if (_initialized)
{
//Determine if this window should be promoted
if (_windowArray.length <= 1 ||
(_isNewWindowPromotedToMain ? _windowArray[_windowArray.length - 1] : _windowArray[0]) === _windowId)
{
_isMainWindow = true;
}
else
{
_isMainWindow = false;
}
}
else
{
if (_windowArray.length === 0)
{
_isMainWindow = true;
_windowArray[0] = _windowId;
localStorage.setItem(_LOCALSTORAGE_KEY, JSON.stringify(_windowArray));
}
else
{
_isMainWindow = false;
_windowArray.push(_windowId);
localStorage.setItem(_LOCALSTORAGE_KEY, JSON.stringify(_windowArray));
}
}
//If the window state has been updated invoke callback
if (_previousState !== _isMainWindow)
{
_onWindowUpdated.call(this);
}
//Perform a recheck of the window on a delay
setTimeout(function()
{
determineWindowState.call(self);
}, RECHECK_WINDOW_DELAY_MS);
}
//Remove the window from the global count
function removeWindow()
{
var __windowArray = JSON.parse(localStorage.getItem(_LOCALSTORAGE_KEY));
for (var i = 0, length = __windowArray.length; i < length; i++)
{
if (__windowArray[i] === _windowId)
{
__windowArray.splice(i, 1);
break;
}
}
//Update the local storage with the new array
localStorage.setItem(_LOCALSTORAGE_KEY, JSON.stringify(__windowArray));
}
//Bind unloading events
function bindUnload()
{
win.addEventListener('beforeunload', function ()
{
if (!_unloaded)
{
removeWindow();
}
});
win.addEventListener('unload', function ()
{
if (!_unloaded)
{
removeWindow();
}
});
}
WindowStateManager.prototype.isMainWindow = function ()
{
return _isMainWindow;
};
WindowStateManager.prototype.resetWindows = function ()
{
localStorage.removeItem(_LOCALSTORAGE_KEY);
};
win.WindowStateManager = WindowStateManager;
})(window);
var WindowStateManager = new WindowStateManager(false, windowUpdated);
function windowUpdated()
{
//"this" is a reference to the WindowStateManager
statusWindow.className = (this.isMainWindow() ? 'main' : 'child');
}
//Resets the count in case something goes wrong in code
//WindowStateManager.resetWindows()
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div id='status'>
<span class='mainWindow'>Main Window</span>
<span class='childWindow'>Child Window</span>
</div>
</body>
</html>
CSS:
#status
{
display:table;
width:100%;
height:500px;
border:1px solid black;
}
span
{
vertical-align:middle;
text-align:center;
margin:0 auto;
font-size:50px;
font-family:arial;
color:#ba3fa3;
display:none;
}
#status.main .mainWindow,
#status.child .childWindow
{
display:table-cell;
}
.mainWindow
{
background-color:#22d86e;
}
.childWindow
{
background-color:#70aeff;
}
(2021) You can use BroadcastChannel to communicate between tabs of the same origin.
For example, put the following at the top level of your js code, then test by opening 2 tabs:
const bc = new BroadcastChannel("my-awesome-site");
bc.onmessage = (event) => {
if (event.data === `Am I the first?`) {
bc.postMessage(`No you're not.`);
alert(`Another tab of this site just got opened`);
}
if (event.data === `No you're not.`) {
alert(`An instance of this site is already running`);
}
};
bc.postMessage(`Am I the first?`);
I know it is late, but maybe help someone
This snippet of code, will detect how many tabs are open and how many are active (visible) and if none of tabs is active, it will choose last opened tab, as active one.
This code will handle windows/tab crash too and it will refresh the count at crash.
Because localStorage is not supported on Stack Overflow currently, please test here.
<html>
<body>
Open in several tabs or windows
<div id="holder_element"></div>
<script type="text/javascript">
//localStorage.clear();
manage_crash();
//Create a windows ID for each windows that is oppened
var current_window_id = Date.now() + "";//convert to string
var time_period = 3000;//ms
//Check to see if PageVisibility API is supported or not
var PV_API = page_visibility_API_check();
/************************
** PAGE VISIBILITY API **
*************************/
function page_visibility_API_check ()
{
var page_visibility_API = false;
var visibility_change_handler = false;
if ('hidden' in document)
{
page_visibility_API = 'hidden';
visibility_change_handler = 'visibilitychange';
}
else
{
var prefixes = ['webkit','moz','ms','o'];
//loop over all the known prefixes
for (var i = 0; i < prefixes.length; i++){
if ((prefixes[i] + 'Hidden') in document)
{
page_visibility_API = prefixes[i] + 'Hidden';
visibility_change_handler = prefixes[i] + 'visibilitychange';
}
}
}
if (!page_visibility_API)
{
//PageVisibility API is not supported in this device
return page_visibility_API;
}
return {"hidden": page_visibility_API, "handler": visibility_change_handler};
}
if (PV_API)
{
document.addEventListener(PV_API.handler, function(){
//console.log("current_window_id", current_window_id, "document[PV_API.hidden]", document[PV_API.hidden]);
if (document[PV_API.hidden])
{
//windows is hidden now
remove_from_active_windows(current_window_id);
//skip_once = true;
}
else
{
//windows is visible now
//add_to_active_windows(current_window_id);
//skip_once = false;
check_current_window_status ();
}
}, false);
}
/********************************************
** ADD CURRENT WINDOW TO main_windows LIST **
*********************************************/
add_to_main_windows_list(current_window_id);
//update active_window to current window
localStorage.active_window = current_window_id;
/**************************************************************************
** REMOVE CURRENT WINDOWS FROM THE main_windows LIST ON CLOSE OR REFRESH **
***************************************************************************/
window.addEventListener('beforeunload', function ()
{
remove_from_main_windows_list(current_window_id);
});
/*****************************
** ADD TO main_windows LIST **
******************************/
function add_to_main_windows_list(window_id)
{
var temp_main_windows_list = get_main_windows_list();
var index = temp_main_windows_list.indexOf(window_id);
if (index < 0)
{
//this windows is not in the list currently
temp_main_windows_list.push(window_id);
}
localStorage.main_windows = temp_main_windows_list.join(",");
return temp_main_windows_list;
}
/**************************
** GET main_windows LIST **
***************************/
function get_main_windows_list()
{
var temp_main_windows_list = [];
if (localStorage.main_windows)
{
temp_main_windows_list = (localStorage.main_windows).split(",");
}
return temp_main_windows_list;
}
/**********************************************
** REMOVE WINDOWS FROM THE main_windows LIST **
***********************************************/
function remove_from_main_windows_list(window_id)
{
var temp_main_windows_list = [];
if (localStorage.main_windows)
{
temp_main_windows_list = (localStorage.main_windows).split(",");
}
var index = temp_main_windows_list.indexOf(window_id);
if (index > -1) {
temp_main_windows_list.splice(index, 1);
}
localStorage.main_windows = temp_main_windows_list.join(",");
//remove from active windows too
remove_from_active_windows(window_id);
return temp_main_windows_list;
}
/**************************
** GET active_windows LIST **
***************************/
function get_active_windows_list()
{
var temp_active_windows_list = [];
if (localStorage.actived_windows)
{
temp_active_windows_list = (localStorage.actived_windows).split(",");
}
return temp_active_windows_list;
}
/*************************************
** REMOVE FROM actived_windows LIST **
**************************************/
function remove_from_active_windows(window_id)
{
var temp_active_windows_list = get_active_windows_list();
var index = temp_active_windows_list.indexOf(window_id);
if (index > -1) {
temp_active_windows_list.splice(index, 1);
}
localStorage.actived_windows = temp_active_windows_list.join(",");
return temp_active_windows_list;
}
/********************************
** ADD TO actived_windows LIST **
*********************************/
function add_to_active_windows(window_id)
{
var temp_active_windows_list = get_active_windows_list();
var index = temp_active_windows_list.indexOf(window_id);
if (index < 0)
{
//this windows is not in active list currently
temp_active_windows_list.push(window_id);
}
localStorage.actived_windows = temp_active_windows_list.join(",");
return temp_active_windows_list;
}
/*****************
** MANAGE CRASH **
******************/
//If the last update didn't happened recently (more than time_period*2)
//we will clear saved localStorage's data and reload the page
function manage_crash()
{
if (localStorage.last_update)
{
if (parseInt(localStorage.last_update) + (time_period * 2) < Date.now())
{
//seems a crash came! who knows!?
//localStorage.clear();
localStorage.removeItem('main_windows');
localStorage.removeItem('actived_windows');
localStorage.removeItem('active_window');
localStorage.removeItem('last_update');
location.reload();
}
}
}
/********************************
** CHECK CURRENT WINDOW STATUS **
*********************************/
function check_current_window_status(test)
{
manage_crash();
if (PV_API)
{
var active_status = "Inactive";
var windows_list = get_main_windows_list();
var active_windows_list = get_active_windows_list();
if (windows_list.indexOf(localStorage.active_window) < 0)
{
//last actived windows is not alive anymore!
//remove_from_main_windows_list(localStorage.active_window);
//set the last added window, as active_window
localStorage.active_window = windows_list[windows_list.length - 1];
}
if (! document[PV_API.hidden])
{
//Window's page is visible
localStorage.active_window = current_window_id;
}
if (localStorage.active_window == current_window_id)
{
active_status = "Active";
}
if (active_status == "Active")
{
active_windows_list = add_to_active_windows(current_window_id);
}
else
{
active_windows_list = remove_from_active_windows(current_window_id);
}
console.log(test, active_windows_list);
var element_holder = document.getElementById("holder_element");
element_holder.insertAdjacentHTML("afterbegin", "<div>"+element_holder.childElementCount+") Current Windows is "+ active_status +" "+active_windows_list.length+" window(s) is visible and active of "+ windows_list.length +" windows</div>");
}
else
{
console.log("PageVisibility API is not supported :(");
//our INACTIVE pages, will remain INACTIVE forever, you need to make some action in this case!
}
localStorage.last_update = Date.now();
}
//check storage continuously
setInterval(function(){
check_current_window_status ();
}, time_period);
//initial check
check_current_window_status ();
</script>
</body>
</html>
I would like to ask if it is possible to build Chrome or Greasemonkey script witch could open all popups in queue. So far i have 2 seperate scripts for this, but that is not working well since popups have anti-spam feature that don't allow too much of them at the same time.
What i would like to do is to process array of popup links in queue fashion and only open next when previous is closed. I have no expirience when it goes down to queues and any kind of event binding.
So resources i got:
1) Array of links already prepared
var URL_Array = [];
$('form[name="form_gallery"] .img img').each(function(i,e){
// Format URL array here
if($(this).closest('.object').children('.phs_voted_count').length == 0){
var string = e.src;
var nowBrake = string.substring(string.length-7,7);
var splited = nowBrake.split('/');
var urlStr = '/window/friend/gallery_view/'+splited[3]+'/'+splited[4]+'.html';
URL_Array[i] = urlStr;
}
});
2) Script that votes on image in popup
/*######################################################*/
var voteBy = '#vte_mark_12'; // Prefered vote icon
var voteDefault = '#vte_mark_5'; // Default vote icon
var voteFormLoc = 'image_voting'; // Image voting popups form
var buyExtraVote = 'image_voting_buy'; // If run out of votes buy more
var captchaLoc = 'input[name="captcha"]'; // Captcha input field
var captchaTxt = 'Enter captcha text!'; // Captcha alert text
var simpatyFormId = '#sym_send'; // Simpaty window form
var startScript = true;
var formProcessedAlready = false; // Used to check if image already was voted
/*######################################################*/
$(function(){
if(startScript){
if($(captchaLoc).length > 0){
alert(captchaTxt);
$(captchaLoc).focus().css('border', '2px solid red');
return false;
}else{
if($('#50').length > 0){
$('#50').attr('checked', true);
$('form').attr('id', buyExtraVote);
$('#'+buyExtraVote).submit();
}else{
$('form').attr('id', voteFormLoc);
if($(voteBy).length > 0){
$(voteBy).attr('checked', true);
setTimeout("$('#"+voteFormLoc+"').submit()", 2000);
}else if($(voteDefault).length > 0){
$(voteDefault).attr('checked', true);
setTimeout("$('#"+voteFormLoc+"').submit()", 2000);
}else{
// If we have simpaty box autocast submit
if($(simpatyFormId).length > 0){
if($(captchaLoc).length > 0){
alert(captchaTxt);
$(captchaLoc).focus().css('border', '2px solid red');
return false;
}else{
$(simpatyFormId).submit();
formProcessedAlready = true;
}
}else{
formProcessedAlready = true;
}
}
}
}
if(formProcessedAlready){
self.close();
}
}
});
As far as i can understand it should go like this:
1) Get all unvoted urls and form array (done)
2) Queue all popups to open
3) Start first popup
4) Voting done and popup closes (done)
5) Start second popup
6) When array finished switch to next page (done)
What you think?
What are the exact URL's of the main page(s) and also of the popups?
What version of jQuery are you using, and how are you including it?
The exact URLs are important because the script needs to handle both the main pages and the popups and operate differently on each.
Their are 2 main ways to handle this. Either:
Use include directives to make sure that the script runs on both the main page and the popup, but switches its behavior depending on the page type. This will have two different instances of the script running simultaneously, which is not a problem.
Use include and possibly exclude directives to ensure that the script only runs on the main page. Then have the popup-opening code manipulate the form.
Here's how to do approach 1:
(1) Suppose the main pages were like:
somewhere.com/main/*
and the popup pages were like:
somewhere.com/window/friend/gallery_view/*
Make sure the script's include-directives fire on both sets of pages.
(2) Ensure that jQuery is available on both kinds of pages. jQuery 1.5.1 is recommended. jQuery 1.3.2 probably won't work for the following code.
(3) Then code like the following should work:
var URL_Array = [];
var PopupQueue = $({}); //-- jQuery on an empty object - a perfect queue holder
//--- Is this a popup window or the main page?
if ( /\/window\/friend\/gallery_view\//i.test (window.location.href) )
{
//--- This is a popup page
/*######################################################*/
var voteBy = '#vte_mark_12'; // Prefered vote icon
var voteDefault = '#vte_mark_5'; // Default vote icon
var voteFormLoc = 'image_voting'; // Image voting popups form
var buyExtraVote = 'image_voting_buy'; // If run out of votes buy more
var captchaLoc = 'input[name="captcha"]'; // Captcha input field
var captchaTxt = 'Enter captcha text!'; // Captcha alert text
var simpatyFormId = '#sym_send'; // Simpaty window form
var startScript = true;
var formProcessedAlready = false; // Used to check if image already was voted
/*######################################################*/
$(function(){
if(startScript){
if($(captchaLoc).length > 0){
alert(captchaTxt);
$(captchaLoc).focus().css('border', '2px solid red');
return false;
}else{
if($('#50').length > 0){
$('#50').attr('checked', true);
$('form').attr('id', buyExtraVote);
$('#'+buyExtraVote).submit();
}else{
$('form').attr('id', voteFormLoc);
if($(voteBy).length > 0){
$(voteBy).attr('checked', true);
setTimeout("$('#"+voteFormLoc+"').submit()", 2000);
}else if($(voteDefault).length > 0){
$(voteDefault).attr('checked', true);
setTimeout("$('#"+voteFormLoc+"').submit()", 2000);
}else{
// If we have simpaty box autocast submit
if($(simpatyFormId).length > 0){
if($(captchaLoc).length > 0){
alert(captchaTxt);
$(captchaLoc).focus().css('border', '2px solid red');
return false;
}else{
$(simpatyFormId).submit();
formProcessedAlready = true;
}
}else{
formProcessedAlready = true;
}
}
}
}
if(formProcessedAlready){
self.close();
}
}
});
}
else
{ //--- This is a main page
$('form[name="form_gallery"] .img img').each(function(i,e){
// Format URL array here
if($(this).closest('.object').children('.phs_voted_count').length == 0){
var string = e.src;
var nowBrake = string.substring(string.length-7,7);
var splited = nowBrake.split('/');
var urlStr = '/window/friend/gallery_view/'+splited[3]+'/'+splited[4]+'.html';
URL_Array[i] = urlStr;
}
});
//--- Load up the queue.
$.each (URL_Array, function (PopupNum, PopupURL) {
PopupQueue.queue ('Popups', function (NextQ_Item) {
OpenPopupFromQueue (NextQ_Item, PopupNum+1, PopupURL);
} );
} );
//--- Launch the Popups, one at a time.
PopupQueue.dequeue ('Popups');
}
function OpenPopupFromQueue (NextQ_Item, PopupNum, PopupURL)
{
var PopupWin = window.open (PopupURL, "_blank");
if (!PopupWin)
{
console.log ('Bad URL ' + PopupURL)
setTimeout (function() { NextQ_Item (); }, 2003);
return;
}
/*--- Only after the popup has loaded can we do any processing.
*/
PopupWin.addEventListener (
"load",
function () {
/*--- Setup the listener for when the popup has closed.
We fire the next popup from the queue, there.
*/
PopupWin.addEventListener (
"unload",
function () {
PopupClosed (NextQ_Item);
},
false
);
/*--- We could process the popup here, but it's better to let another instance of this
script do it, instead.
*/
},
false
);
}
function PopupClosed (NextQ_Item)
{
//--- Launch the next popup from the queue.
NextQ_Item ();
}
You could do something like:
var links = get_your_links();
function process_one() {
if(links.length > 0) {
show_popup(links.pop(), process_one);
}
}
function show_popup(link, callback) {
var popup = window.open(link, "mywindow", "width=100,height=100");
$(popup).bind("beforeunload", function() {
process_one();
return true;
})
}
I hope it helps...