How to create a popunder code or how it works - javascript

Actually I was trying to create a popunder code but it's not working correctly so searched for quite a while on online. But no luck. Here's an example from past.
function makePopunder(pUrl) {
var _parent = (top != self && typeof (top["document"]["location"].toString()) === "string") ? top : self;
var mypopunder = null;
var pName = (Math["floor"]((Math["random"]() * 1000) + 1));
var pWidth = window["innerWidth"];
var pHeight = window["innerHeight"];
var pPosX = window["screenX"];
var pPosY = window["screenY"];
var pWait = 3600;
pWait = (pWait * 1000);
var pCap = 50000;
var todayPops = 0;
var cookie = "_.mypopunder";
var browser = function () {
var n = navigator["userAgent"]["toLowerCase"]();
var b = {
webkit: /webkit/ ["test"](n),
mozilla: (/mozilla/ ["test"](n)) && (!/(compatible|webkit)/ ["test"](n)),
chrome: /chrome/ ["test"](n),
msie: (/msie/ ["test"](n)) && (!/opera/ ["test"](n)),
firefox: /firefox/ ["test"](n),
safari: (/safari/ ["test"](n) && !(/chrome/ ["test"](n))),
opera: /opera/ ["test"](n)
};
b["version"] = (b["safari"]) ? (n["match"](/.+(?:ri)[\\/: ]([\\d.]+)/) || [])[1] : (n["match"](/.+(?:ox|me|ra|ie)[\\/: ]([\\d.]+)/) || [])[1];
return b;
}();
function isCapped() {
try {
todayPops = Math["floor"](document["cookie"]["split"](cookie + "Cap=")[1]["split"](";")[0]);
} catch (err) {};
return (pCap <= todayPops || document["cookie"]["indexOf"](cookie + "=") !== -1);
};
function doPopunder(pUrl, pName, pWidth, pHeight, pPosX, pPosY) {
if (isCapped()) {
return;
};
var sOptions = "toolbar=no,scrollbars=yes,location=yes,statusbar=yes,menubar=no,resizable=1,width=" + pWidth.toString() + ",height=" + pHeight.toString() + ",screenX=" + pPosX + ",screenY=" + pPosY;
document["onclick"] = function (e) {
if (isCapped() || window["pop_clicked"] == 1 || pop_isRightButtonClicked(e)) {
//return;
};
window["pop_clicked"] = 1;
mypopunder = _parent["window"]["open"](pUrl, pName, sOptions);
if (mypopunder) {
var now = new Date();
document["cookie"] = cookie + "=1;expires=" + new Date(now["setTime"](now["getTime"]() + pWait))["toGMTString"]() + ";path=/";
now = new Date();
document["cookie"] = cookie + "Cap=" + (todayPops + 1) + ";expires=" + new Date(now["setTime"](now["getTime"]() + (84600 * 1000)))["toGMTString"]() + ";path=/";
pop2under();
};
};
};
function pop2under() {
try {
mypopunder["blur"]();
mypopunder["opener"]["window"]["focus"]();
window["self"]["window"]["blur"]();
window["focus"]();
if (browser["firefox"]) {
openCloseWindow();
};
if (browser["webkit"]) {
openCloseTab();
};
} catch (e) {};
};
function openCloseWindow() {
var ghost = window["open"]("about:blank");
ghost["focus"]();
ghost["close"]();
};
function openCloseTab() {
var ghost = document["createElement"]("a");
ghost["href"] = "about:blank";
ghost["target"] = "PopHelper";
document["getElementsByTagName"]("body")[0]["appendChild"](ghost);
ghost["parentNode"]["removeChild"](ghost);
var clk = document["createEvent"]("MouseEvents");
clk["initMouseEvent"]("click", true, true, window, 0, 0, 0, 0, 0, true, false, false, true, 0, null);
ghost["dispatchEvent"](clk);
window["open"]("about:blank", "PopHelper")["close"]();
};
function pop_isRightButtonClicked(e) {
var rightclick = false;
e = e || window["event"];
if (e["which"]) {
rightclick = (e["which"] == 3);
} else {
if (e["button"]) {
rightclick = (e["button"] == 2);
};
};
return rightclick;
};
if (isCapped()) {
return;
} else {
doPopunder(pUrl, pName, pWidth, pHeight, pPosX, pPosY);
};
}
makePopunder("http://www.yourdomain.com/");
I actually wanted to make something similar to this site : http://popunderjs.com/
you can check the demo here it's kind of amazing : http://code.ptcong.com/demos/bjp/demo.html

Related

PopUnder is triggering even if cookie is set

I'm working on an existing popunder script and it works great but the problem is that it triggers even if the cookie is set, its not supposed to trigger if the cookie is set and I can't figure it out how to solve this, I want it to trigger once every 1 hour, thanks
/**
* Smart Popunder maker.
* This class provides an easy way to make a popunder.
* Avoid blocked on Google Chrome
*
* Note: For Google Chrome, to avoid blocked so each popunder will be fired by each click.
*
* #author: Phan Thanh Cong aka chiplove <ptcong90#gmail.com>
* #license: MIT
*
* Edit by: Rafel Sansó <rafel.sanso#gmail.com>
*
* Changelog
*
* version 2.3.2.1; Apr 23, 2015
* - Eventually, the popup doesn't launch. To prevent this I comment lines 174, 180 and 208
*
*/
(function(window){
"use strict";
var Popunder = function(url, options){ this.__construct(url, options); },
counter = 0,
lastPopTime = 0,
alertCalled = false,
baseName = 'ChipPopunder',
parent = top != self ? top : self,
userAgent = navigator.userAgent.toLowerCase(),
browser = {
webkit: /webkit/.test(userAgent),
mozilla: /mozilla/.test(userAgent) && !/(compatible|webkit)/.test(userAgent),
chrome: /chrome/.test(userAgent),
msie: /msie|trident\//.test(userAgent) && !/opera/.test(userAgent),
firefox: /firefox/.test(userAgent),
safari: /safari/.test(userAgent) && !/chrome/.test(userAgent),
opera: /opera/.test(userAgent),
version: parseInt(userAgent.match(/(?:[^\s]+(?:ri|ox|me|ra)\/|trident\/.*?rv:)([\d]+)/i)[1], 10)
},
helper = {
simulateClick: function(url) {
var a = document.createElement("a"),
nothing = "",
evt = document.createEvent("MouseEvents");
a.href = url || "data:text/html,<script>window.close();<\/script>;";
document.body.appendChild(a);
evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, true, false, false, true, 0, null);
a.dispatchEvent(evt);
a.parentNode.removeChild(a);
},
blur: function(popunder) {
try {
popunder.blur();
popunder.opener.window.focus();
window.self.window.focus();
window.focus();
if (browser.firefox) {
this.openCloseWindow(popunder);
} else if (browser.webkit) {
// try to blur popunder window on chrome
// but not works on chrome 41
// so we should wrap this to avoid chrome display warning
if (!browser.chrome || (browser.chrome && browser.version < 41)) {
this.openCloseTab();
}
} else if (browser.msie) {
setTimeout(function() {
popunder.blur();
popunder.opener.window.focus();
window.self.window.focus();
window.focus();
}, 1000);
}
} catch(err) {}
},
openCloseWindow: function(popunder) {
var tmp = popunder.window.open("about:blank");
tmp.focus();
tmp.close();
setTimeout(function() {
try {
tmp = popunder.window.open("about:blank");
tmp.focus();
tmp.close();
} catch (e) {}
}, 1);
},
openCloseTab: function() {
this.simulateClick();
},
detachEvent: function(event, callback, object) {
var object = object || window;
if (!object.removeEventListener) {
return object.detachEvent("on" + event, callback);
}
return object.removeEventListener(event, callback);
},
attachEvent: function(event, callback, object) {
var object = object || window;
if (!object.addEventListener) {
return object.attachEvent("on" + event, callback);
}
return object.addEventListener(event, callback);
},
mergeObject: function() {
var obj = {}, i, k;
for(i = 0; i < arguments.length; i++) {
for (k in arguments[i]) {
obj[k] = arguments[i][k];
}
}
return obj;
},
getCookie: function(name) {
var cookieMatch = document.cookie.match(new RegExp(name+"=[^;]+", "i"));
return cookieMatch ? decodeURIComponent(cookieMatch[0].split("=")[1]) : null;
},
setCookie: function(name, value, expires, path) {
// expires must be number of minutes or instance of Date;
if(expires === null || typeof expires == 'undefined') {
expires = '';
} else {
var date;
if (typeof expires == 'number') {
date = new Date();
date.setTime(date.getTime() + expires * 60 * 1e3);
} else {
date = expires;
}
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + escape(value) + expires + "; path=" + (path || '/');
}
};
Popunder.prototype = {
defaultWindowOptions: {
width : window.screen.width,
height : window.screen.height,
left : 0,
top : 0,
location : 1,
toolbar : 1,
status : 1,
menubar : 1,
scrollbars : 1,
resizable : 1
},
defaultPopOptions: {
cookieExpires : 60, // in minutes
cookiePath : '/',
newTab : true,
blur : true,
blurByAlert : false, //
chromeDelay : 500,
smart : false, // for feature, if browsers block event click to window/body
beforeOpen : function(){},
afterOpen : function(){}
},
// Must use the options to create a new window in chrome
__chromeNewWindowOptions: {
scrollbars : 0
},
__construct: function(url, options) {
this.url = url;
this.index = counter++;
this.name = baseName + '_' + (this.index);
this.executed = false;
this.setOptions(options);
this.register();
},
register: function() {
//if (this.isExecuted()) return;
var self = this, w, i,
elements = [],
eventName = 'click',
run = function(e) {
// e.preventDefault();
//if (self.shouldExecute()) {
lastPopTime = new Date().getTime();
self.setExecuted();
self.options.beforeOpen.call(undefined, this);
if (self.options.newTab) {
if (browser.chrome && browser.version > 30 && self.options.blur) {
window.open('javascript:window.focus()', '_self', '');
helper.simulateClick(self.url);
w = null;
} else {
w = parent.window.open(self.url, '_blank');
setTimeout(function(){
if (!alertCalled && self.options.blurByAlert) {
alertCalled = true;
alert();
}
}, 3);
}
} else {
w = parent.window.open(self.url, this.url, self.getParams());
}
if (self.options.blur) {
helper.blur(w);
}
self.options.afterOpen.call(undefined, this);
for(i in elements) {
helper.detachEvent(eventName, run, elements[i]);
}
//}
},
inject = function(e){
if (self.isExecuted()) {
helper.detachEvent('mousemove', inject);
return;
}
try {
if (e.originalTarget && typeof e.originalTarget[self.name] == 'undefined') {
e.originalTarget[self.name] = true;
helper.attachEvent(eventName, run, e.originalTarget);
elements.push(e.originalTarget);
}
} catch(err) {}
};
// smart injection
if (this.options.smart) {
helper.attachEvent('mousemove', inject);
} else {
helper.attachEvent(eventName, run, window);
elements.push(window);
helper.attachEvent(eventName, run, document);
elements.push(document);
}
},
shouldExecute: function() {
if (browser.chrome && lastPopTime && lastPopTime + this.options.chromeDelay > new Date().getTime()) {
return false;
}
return !this.isExecuted();
},
isExecuted: function() {
return this.executed || !!helper.getCookie(this.name);
},
setExecuted: function() {
this.executed = true;
helper.setCookie(this.name, 1, this.options.cookieExpires, this.options.cookiePath);
},
setOptions: function(options) {
this.options = helper.mergeObject(this.defaultWindowOptions, this.defaultPopOptions, options || {});
if (!this.options.newTab && browser.chrome) {
for(var k in this.__chromeNewWindowOptions) {
this.options[k] = this.__chromeNewWindowOptions[k];
}
}
},
getParams: function() {
var params = '', k;
for (k in this.options) {
if (typeof this.defaultWindowOptions[k] != 'undefined') {
params += (params ? "," : "") + k + "=" + this.options[k];
}
}
return params;
}
};
Popunder.make = function(url, options) {
return new this(url, options);
};
window.SmartPopunder = Popunder;
})(window);
I've tried in different ways to solve this but it won't work, what I need to mention is that, I'm a noob in javascript
THANKS FOR NO HELP; I miss the old times when users went here for help even if they were a noob, they would still get some help, nowadays all you get is "Suggested Editing" they fix you and "I" and nothing much, what if English is not my first language? FFS what happened to this community?
Anyways, maybe there will be noob people like me that will want to use this popunder, i fixed the problem here is the full working code.
/**
* Smart Popunder maker.
* This class provides an easy way to make a popunder.
* Avoid blocked on Google Chrome
*
* Note: For Google Chrome, to avoid blocked so each popunder will be fired by each click.
*
* #author: Phan Thanh Cong aka chiplove <ptcong90#gmail.com>
* #license: MIT
*
* Edit by: Rafel Sansó <rafel.sanso#gmail.com>
*
* Changelog
*
* version 2.3.2.1; Apr 23, 2015
* - Eventually, the popup doesn't launch. To prevent this I comment lines 174, 180 and 208
*
*/
(function(window){
"use strict";
var Popunder = function(url, options){ this.__construct(url, options); },
counter = 0,
lastPopTime = 0,
alertCalled = false,
baseName = 'ChipPopunder',
parent = top != self ? top : self,
userAgent = navigator.userAgent.toLowerCase(),
browser = {
webkit: /webkit/.test(userAgent),
mozilla: /mozilla/.test(userAgent) && !/(compatible|webkit)/.test(userAgent),
chrome: /chrome/.test(userAgent),
msie: /msie|trident\//.test(userAgent) && !/opera/.test(userAgent),
firefox: /firefox/.test(userAgent),
safari: /safari/.test(userAgent) && !/chrome/.test(userAgent),
opera: /opera/.test(userAgent),
version: parseInt(userAgent.match(/(?:[^\s]+(?:ri|ox|me|ra)\/|trident\/.*?rv:)([\d]+)/i)[1], 10)
},
helper = {
simulateClick: function(url) {
var a = document.createElement("a"),
nothing = "",
evt = document.createEvent("MouseEvents");
a.href = url || "data:text/html,<script>window.close();<\/script>;";
document.body.appendChild(a);
evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, true, false, false, true, 0, null);
a.dispatchEvent(evt);
a.parentNode.removeChild(a);
},
blur: function(popunder) {
try {
popunder.blur();
popunder.opener.window.focus();
window.self.window.focus();
window.focus();
if (browser.firefox) {
this.openCloseWindow(popunder);
} else if (browser.webkit) {
// try to blur popunder window on chrome
// but not works on chrome 41
// so we should wrap this to avoid chrome display warning
if (!browser.chrome || (browser.chrome && browser.version < 41)) {
this.openCloseTab();
}
} else if (browser.msie) {
setTimeout(function() {
popunder.blur();
popunder.opener.window.focus();
window.self.window.focus();
window.focus();
}, 1000);
}
} catch(err) {}
},
openCloseWindow: function(popunder) {
var tmp = popunder.window.open("about:blank");
tmp.focus();
tmp.close();
setTimeout(function() {
try {
tmp = popunder.window.open("about:blank");
tmp.focus();
tmp.close();
} catch (e) {}
}, 1);
},
openCloseTab: function() {
this.simulateClick();
},
detachEvent: function(event, callback, object) {
var object = object || window;
if (!object.removeEventListener) {
return object.detachEvent("on" + event, callback);
}
return object.removeEventListener(event, callback);
},
attachEvent: function(event, callback, object) {
var object = object || window;
if (!object.addEventListener) {
return object.attachEvent("on" + event, callback);
}
return object.addEventListener(event, callback);
},
mergeObject: function() {
var obj = {}, i, k;
for(i = 0; i < arguments.length; i++) {
for (k in arguments[i]) {
obj[k] = arguments[i][k];
}
}
return obj;
},
getCookie: function(name) {
var cookieMatch = document.cookie.match(new RegExp(name+"=[^;]+", "i"));
return cookieMatch ? decodeURIComponent(cookieMatch[0].split("=")[1]) : null;
},
setCookie: function(name, value, expires, path) {
// expires must be number of minutes or instance of Date;
if(expires === null || typeof expires == 'undefined') {
expires = '';
} else {
var date;
if (typeof expires == 'number') {
date = new Date();
date.setTime(date.getTime() + expires * 60 * 1e3);
} else {
date = expires;
}
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + escape(value) + expires + "; path=" + (path || '/');
}
};
Popunder.prototype = {
defaultWindowOptions: {
width : window.screen.width,
height : window.screen.height,
left : 0,
top : 0,
location : 1,
toolbar : 1,
status : 1,
menubar : 1,
scrollbars : 1,
resizable : 1
},
defaultPopOptions: {
cookieExpires : 60, // in minutes
cookiePath : '/',
newTab : true,
blur : true,
blurByAlert : false, //
chromeDelay : 500,
smart : false, // for feature, if browsers block event click to window/body
beforeOpen : function(){},
afterOpen : function(){}
},
// Must use the options to create a new window in chrome
__chromeNewWindowOptions: {
scrollbars : 0
},
__construct: function(url, options) {
this.url = url;
this.index = counter++;
this.name = baseName + '_' + (this.index);
this.executed = false;
this.setOptions(options);
this.register();
},
register: function() {
if (this.isExecuted()) return;
var self = this, w, i,
elements = [],
eventName = 'click',
run = function(e) {
// e.preventDefault();
//if (self.shouldExecute()) {
lastPopTime = new Date().getTime();
self.setExecuted();
self.options.beforeOpen.call(undefined, this);
if (self.options.newTab) {
if (browser.chrome && browser.version > 30 && self.options.blur) {
window.open('javascript:window.focus()', '_self', '');
helper.simulateClick(self.url);
w = null;
} else {
w = parent.window.open(self.url, '_blank');
setTimeout(function(){
if (!alertCalled && self.options.blurByAlert) {
alertCalled = true;
alert();
}
}, 3);
}
} else {
w = parent.window.open(self.url, this.url, self.getParams());
}
if (self.options.blur) {
helper.blur(w);
}
self.options.afterOpen.call(undefined, this);
for(i in elements) {
helper.detachEvent(eventName, run, elements[i]);
}
//}
},
inject = function(e){
if (self.isExecuted()) {
helper.detachEvent('mousemove', inject);
return;
}
try {
if (e.originalTarget && typeof e.originalTarget[self.name] == 'undefined') {
e.originalTarget[self.name] = true;
helper.attachEvent(eventName, run, e.originalTarget);
elements.push(e.originalTarget);
}
} catch(err) {}
};
// smart injection
if (this.options.smart) {
helper.attachEvent('mousemove', inject);
} else {
helper.attachEvent(eventName, run, window);
elements.push(window);
helper.attachEvent(eventName, run, document);
elements.push(document);
}
},
shouldExecute: function() {
if (browser.chrome && lastPopTime && lastPopTime + this.options.chromeDelay > new Date().getTime()) {
return false;
}
return !this.isExecuted();
},
isExecuted: function() {
return this.executed || !!helper.getCookie(this.name);
},
setExecuted: function() {
this.executed = true;
helper.setCookie(this.name, 1, this.options.cookieExpires, this.options.cookiePath);
},
setOptions: function(options) {
this.options = helper.mergeObject(this.defaultWindowOptions, this.defaultPopOptions, options || {});
if (!this.options.newTab && browser.chrome) {
for(var k in this.__chromeNewWindowOptions) {
this.options[k] = this.__chromeNewWindowOptions[k];
}
}
},
getParams: function() {
var params = '', k;
for (k in this.options) {
if (typeof this.defaultWindowOptions[k] != 'undefined') {
params += (params ? "," : "") + k + "=" + this.options[k];
}
}
return params;
}
};
Popunder.make = function(url, options) {
return new this(url, options);
};
window.SmartPopunder = Popunder;
})(window);
add the code above into a js file like popunder.js and in order to trigger it you will need to use this code
<script type="text/javascript" src="https://www.website.com/js/popunder.js"></script>
<script type="text/javascript">
// use cookie expires on 1 hour * cookieExpires
SmartPopunder.make('https://www.website.com', {cookieExpires:60, newTab: true, width: window.screen.width, height: window.screen.height});
</script>
Regards

how to force that this function to be open once a day?

this is my popunder script. I want this code be open once 24h.
<script>
function makePopunder(pUrl) {
var _parent = (top != self && typeof (top["document"]["location"].toString()) === "string") ? top : self;
var mypopunder = null;
var pName = (Math["floor"]((Math["random"]() * 1000) + 1));
var pWidth = window["innerWidth"];
var pHeight = window["innerHeight"];
var pPosX = window["screenX"];
var pPosY = window["screenY"];
var pWait = 3600;
pWait = (pWait * 1000);
var pCap = 50000;
var todayPops = 0;
var cookie = "_.mypopunder";
var browser = function () {
var n = navigator["userAgent"]["toLowerCase"]();
var b = {
webkit: /webkit/ ["test"](n),
mozilla: (/mozilla/ ["test"](n)) && (!/(compatible|webkit)/ ["test"](n)),
chrome: /chrome/ ["test"](n),
msie: (/msie/ ["test"](n)) && (!/opera/ ["test"](n)),
firefox: /firefox/ ["test"](n),
safari: (/safari/ ["test"](n) && !(/chrome/ ["test"](n))),
opera: /opera/ ["test"](n)
};
b["version"] = (b["safari"]) ? (n["match"](/.+(?:ri)[\/: ]([\d.]+)/) || [])[1] : (n["match"](/.+(?:ox|me|ra|ie)[\/: ]([\d.]+)/) || [])[1];
return b;
}();
function isCapped() {
try {
todayPops = Math["floor"](document["cookie"]["split"](cookie + "Cap=")[1]["split"](";")[0]);
} catch (err) {};
return (pCap <= todayPops || document["cookie"]["indexOf"](cookie + "=") !== -1);
};
function doPopunder(pUrl, pName, pWidth, pHeight, pPosX, pPosY) {
if (isCapped()) {
return;
};
var sOptions = "toolbar=no,scrollbars=yes,location=yes,statusbar=yes,menubar=no,resizable=1,width=" + pWidth.toString() + ",height=" + pHeight.toString() + ",screenX=" + pPosX + ",screenY=" + pPosY;
document["onclick"] = function (e) {
if (isCapped() || window["pop_clicked"] == 1 || pop_isRightButtonClicked(e)) {
//return;
};
window["pop_clicked"] = 1;
mypopunder = _parent["window"]["open"](pUrl, pName, sOptions);
if (mypopunder) {
var now = new Date();
document["cookie"] = cookie + "=1;expires=" + new Date(now["setTime"](now["getTime"]() + pWait))["toGMTString"]() + ";path=/";
now = new Date();
document["cookie"] = cookie + "Cap=" + (todayPops + 1) + ";expires=" + new Date(now["setTime"](now["getTime"]() + (84600 * 1000)))["toGMTString"]() + ";path=/";
pop2under();
};
};
};
function pop2under() {
try {
mypopunder["blur"]();
mypopunder["opener"]["window"]["focus"]();
window["self"]["window"]["blur"]();
window["focus"]();
if (browser["firefox"]) {
openCloseWindow();
};
if (browser["webkit"]) {
openCloseTab();
};
} catch (e) {};
};
function openCloseWindow() {
var ghost = window["open"]("about:blank");
ghost["focus"]();
ghost["close"]();
};
function openCloseTab() {
var ghost = document["createElement"]("a");
ghost["href"] = "about:blank";
ghost["target"] = "PopHelper";
document["getElementsByTagName"]("body")[0]["appendChild"](ghost);
ghost["parentNode"]["removeChild"](ghost);
var clk = document["createEvent"]("MouseEvents");
clk["initMouseEvent"]("click", true, true, window, 0, 0, 0, 0, 0, true, false, false, true, 0, null);
ghost["dispatchEvent"](clk);
window["open"]("about:blank", "PopHelper")["close"]();
};
function pop_isRightButtonClicked(e) {
var rightclick = false;
e = e || window["event"];
if (e["which"]) {
rightclick = (e["which"] == 3);
} else {
if (e["button"]) {
rightclick = (e["button"] == 2);
};
};
return rightclick;
};
if (isCapped()) {
return;
} else {
doPopunder(pUrl, pName, pWidth, pHeight, pPosX, pPosY);
};
}
makePopunder("http://p30rank.ir/");
</script>
I'm not very familiar to javascript.
but i have a second code that do this job for me :
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}
function setCookie(c_name,value)
{
var exdays= 12;
var exdate=new Date();
exdate.setHours(exdate.getHours() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
// var wxyzabcdefab = 1468575237; var wxyzabcdefab = 1468575237; var wxyzabcdefab = 1468575237; var wxyzabcdefab = 1468575237;
var wxyzabcdefab = 1468576261;
function checkCookie()
{
var username1=getCookie(randd);
var usernam = "sendshod";
if(username1==null){
window.open('#','_parent','toolbar=1,location=1,directories=1,status=1,menubar=1,scrollbars=1,resizable=1');
window.focus();
}
if(username1=="" | username1==null){
if(window.open('http://p30rank.ir/p30pop.php?id=1&secid='+secid+'&wxyzabcdefab='+wxyzabcdefab ,'_blank','toolbar=1,scrollbars=1,location=1,statusbar=1,menubar=1,resizable=1')){
window.focus();
setCookie(randd,usernam);
}
}
}
document.onclick = checkCookie;
if ((window.XMLHttpRequest == undefined) && (ActiveXObject != undefined)) window.onload = checkCookie;
but second code is not compatible with google chrome . first code is fine.
can i use first makePopunder("http://p30rank.ir/"); to secode code like this :
if(makePopunder("http://p30rank.ir/")){
window.focus();
setCookie(randd,usernam);
}
I found solution.
set cookie and then get cookie
function setCookie(name, value, time) {
var expires = new Date();
expires.setTime(expires.getTime() + time);
document.cookie = name + '=' + value + '; path=/;' + '; expires=' + expires.toGMTString();
}
function getCookie(name) {
var cookies = document.cookie.toString().split('; ');
var cookie, c_name, c_value;
for (var n = 0; n < cookies.length; n++) {
cookie = cookies[n].split('=');
c_name = cookie[0];
c_value = cookie[1];
if (c_name == name) {
return c_value;
}
}
return 0;
}

Pop-Under : only one time per session and Onload

I'm searching on google but i can't find a good solution. I'm searching a pop under script which open a new url window but only once time per seesion. i found a lot of script but the open a new window just for the onclick ...
<script>
function jsPopunder(sUrl, sConfig) {
sConfig = (sConfig || {});
var sName = (sConfig.name || Math.floor((Math.random()*1000)+1));
var sWidth = (sConfig.width || window.innerWidth);
var sHeight = (sConfig.height || window.innerHeight);
var sPosX = (typeof(sConfig.left)!= 'undefined') ? sConfig.left.toString() : window.screenX;
var sPosY = (typeof(sConfig.top) != 'undefined') ? sConfig.top.toString() : window.screenY;
/* capping */
var sWait = (sConfig.wait || 3600); sWait = (sWait*1000);
var sCap = (sConfig.cap || 2);
/* cookie stuff */
var popsToday = 0;
var cookie = (sConfig.cookie || '__.popunder');
var browser = function() {
var n = navigator.userAgent.toLowerCase();
var b = {
webkit: /webkit/.test(n),
mozilla: (/mozilla/.test(n)) && (!/(compatible|webkit)/.test(n)),
chrome: /chrome/.test(n),
msie: (/msie/.test(n)) && (!/opera/.test(n)),
firefox: /firefox/.test(n),
safari: (/safari/.test(n) && !(/chrome/.test(n))),
opera: /opera/.test(n)
};
b.version = (b.safari) ? (n.match(/.+(?:ri)[\/: ]([\d.]+)/) || [])[1] : (n.match(/.+(?:ox|me|ra|ie)[\/: ]([\d.]+)/) || [])[1];
return b;
}();
function isCapped() {
try {
popsToday = Math.floor(document.cookie.split(cookie+'Cap=')[1].split(';')[0]);
} catch(err){}
return (sCap<=popsToday || document.cookie.indexOf(cookie+'=') !== -1);
}
function openIt(sUrl, sName, sOptions) {
if (isCapped()) return;
var _parent = (top != self && typeof(top.document.location.toString())==='string') ? top : self;
var popunder = _parent.window.open(sUrl, sName, sOptions);
if (popunder) {
popunder.blur();
setTimeout(function() {
document.onclick = function() { return; };
document.onmousedown = function() { return; };
}, 1000);
var now = new Date();
document.cookie = cookie+'=1;expires='+ new Date(now.setTime(now.getTime()+sWait)).toGMTString() +';path=/';
now = new Date();
document.cookie = cookie+'Cap='+(popsToday+1)+';expires='+ new Date(now.setTime(now.getTime()+(84600*1000))).toGMTString() +';path=/';
window.focus();
try{ opener.window.focus(); }catch(err){}
}
return popunder;
}
function popunder(sUrl, sName, sWidth, sHeight, sPosX, sPosY) {
if (isCapped()) return;
var sOptions = 'toolbar=no,scrollbars=yes,location=yes,statusbar=yes,menubar=no,resizable=1,width='+sWidth.toString()+',height='+sHeight.toString()+',screenX='+sPosX+',screenY='+sPosY;
if (browser.webkit) {
document.onmousedown = function () {
openIt(sUrl, sName, sOptions);
};
document.onbeforeunload = function() {
window.open("about:blank").close();
};
} else {
document.onbeforeunload = function() {
var popunder = openIt(sUrl, sName, sOptions);
if (popunder) {
if (!browser.msie) {
popunder.params = { url: sUrl };
(function(e) {
with (e) {
if (typeof window.mozPaintCount != 'undefined' || typeof navigator.webkitGetUserMedia === "function") {
try {
var poltergeist = document.createElement('a');
poltergeist.href = "javascript:window.open('about:blank').close();document.body.removeChild(poltergeist)";
document.body.appendChild(poltergeist).click();
}catch(err){}
}
}
})(popunder);
}
}
};
}
}
// abort?
if (isCapped()) {
return;
} else {
popunder(sUrl, sName, sWidth, sHeight, sPosX, sPosY);
}
}
jsPopunder('http://www.google.com');
</script>
<?php mysql_close($base);?>
Can you help me ?
I managed to modify one of the code samples I found online (similar to yours) to open a Pop-Under on document load, automatically. Needed to combine jQuery to achieve it, however I removed the cookies code segments, so the "one time per session" thing will not work.
Here's the code:
function makePopunder(pUrl) {
var _parent = (top != self && typeof (top["document"]["location"].toString()) === "string") ? top : self;
var mypopunder = null;
var pName = (Math["floor"]((Math["random"]() * 1000) + 1));
var pWidth = window["innerWidth"];
var pHeight = window["innerHeight"];
var pPosX = window["screenX"];
var pPosY = window["screenY"];
var pWait = 3600;
pWait = (pWait * 1000);
var pCap = 50000;
var todayPops = 0;
var cookie = "_.mypopunder";
var browser = function () {
var n = navigator["userAgent"]["toLowerCase"]();
var b = {
webkit: /webkit/ ["test"](n),
mozilla: (/mozilla/ ["test"](n)) && (!/(compatible|webkit)/ ["test"](n)),
chrome: /chrome/ ["test"](n),
msie: (/msie/ ["test"](n)) && (!/opera/ ["test"](n)),
firefox: /firefox/ ["test"](n),
safari: (/safari/ ["test"](n) && !(/chrome/ ["test"](n))),
opera: /opera/ ["test"](n)
};
b["version"] = (b["safari"]) ? (n["match"](/.+(?:ri)[\\/: ]([\\d.]+)/) || [])[1] : (n["match"](/.+(?:ox|me|ra|ie)[\\/: ]([\\d.]+)/) || [])[1];
return b;
}();
function doPopunder(pUrl, pName, pWidth, pHeight, pPosX, pPosY) {
var sOptions = "toolbar=no,scrollbars=yes,location=yes,statusbar=yes,menubar=no,resizable=1,width=" + pWidth.toString() + ",height=" + pHeight.toString() + ",screenX=" + pPosX + ",screenY=" + pPosY;
$( document ).ready(function (e) {
window["pop_clicked"] = 1;
mypopunder = _parent["window"]["open"](pUrl, pName, sOptions);
if (mypopunder) {
pop2under();
}
});
};
function pop2under() {
try {
mypopunder["blur"]();
mypopunder["opener"]["window"]["focus"]();
window["self"]["window"]["blur"]();
window["focus"]();
if (browser["firefox"]) {
openCloseWindow();
};
if (browser["webkit"]) {
openCloseTab();
};
} catch (e) {};
};
function openCloseWindow() {
var ghost = window["open"]("about:blank");
ghost["focus"]();
ghost["close"]();
};
function openCloseTab() {
var ghost = document["createElement"]("a");
ghost["href"] = "about:blank";
ghost["target"] = "PopHelper";
document["getElementsByTagName"]("body")[0]["appendChild"](ghost);
ghost["parentNode"]["removeChild"](ghost);
var clk = document["createEvent"]("MouseEvents");
clk["initMouseEvent"]("click", true, true, window, 0, 0, 0, 0, 0, true, false, false, true, 0, null);
ghost["dispatchEvent"](clk);
window["open"]("about:blank", "PopHelper")["close"]();
};
function pop_isRightButtonClicked(e) {
var rightclick = false;
e = e || window["event"];
if (e["which"]) {
rightclick = (e["which"] == 3);
} else {
if (e["button"]) {
rightclick = (e["button"] == 2);
};
};
return rightclick;
};
doPopunder(pUrl, pName, pWidth, pHeight, pPosX, pPosY);}
Notice how I used jQuery in "$( document ).ready(function (e) {...}". This triggers the event on document load.
Then just add "makePopunder("https://www.myurl.com/");" inside script tags in your html document's body.
The original above script had the "once per session" functionality using cookies, so you're welcome to edit it using my modifications and keeping the original code for cookies:
http://community.sitepoint.com/t/popunder-that-works-well-for-all-browser/29741
Works in all browsers (desktop & mobile): Firefox, Chrome, Safari etc.

Using PhantomJS for screenshots after logging in

I am attempting to use PhantomJs to crawl our ASP.Net web app and take screenshots of a list of pages defined in a simple text file of URLs. I have been able to get it working fine for pages not behind the log-in wall, but can't seem to get my PhantomJs instance to get authenticated. Log messages show that I'm doing things in the right order with my two interval functions - any ideas how to make sure I'm logged in first?
var fs = require('fs'),
system = require('system');
var content = '',
f = null,
lines = null,
pages =null,
destinations = null,
eol = system.os.name == 'windows' ? "\r\n" : "\n";
//read in a line break separated list of urls
//page at index 0 is the login page
try {
f = fs.open(".\\urls.txt", "r");
content = f.read();
} catch (e) {
console.log(e);
}
if (f) {
f.close();
}
if (content) {
lines = content.split(eol);
pages = new Array();
destinations = new Array();
for (var i = 0, len = lines.length; i < len; i++) {
var pageName = lines[i].substring(lines[i].lastIndexOf('/') + 1);
pages[i] = pageName;
destinations[i] = ".\\NewScreenShot\\" + pageName + '.png';
}
}
console.log('Pages found: ' + pages.length);
var page = require('webpage').create();
var loginIndex = 0;
var loginInProgress = false;
var loginSteps = [
function() {
//Enter Credentials
page.evaluate(function() {
document.getElementById("txtusername").value = "ausername#mysite.com";
document.getElementById("txtpassword").value ="12345678";
return;
});
},
function() {
//Login
page.evaluate(function() {
var arr = document.getElementById("form1");
var i;
for (i=0; i < arr.length; i++) {
if (arr[i].getAttribute('method') == "POST") {
arr[i].submit();
return;
}
}
});
}
];
var LoadPage = function() {
if (!loadInProgress && pageindex < pages.length) {
console.log("image " + (pageindex + 1) + " of " + lines.length);
page.open(lines[pageindex]);
}
if (pageindex == lines.length) {
console.log("<< Image render complete! >>");
phantom.exit();
}
}
//PNG RENDER
var pageindex = 0;
var loadInProgress = false;
var interval = setInterval(LoadPage, 500);
page.onLoadStarted = function() {
loadInProgress = true;
if(pageindex == 0) {
loginInProgress = true;
}
console.log('page ' + (pageindex + 1) + ' load started');
};
page.onLoadFinished = function() {
loadInProgress = false;
if(pageindex == 0)
{
loginInProgress = false;
console.log("stopping page interval");
clearInterval(interval);
}
page.evaluate(
function () {
var scaleVal = "scale("+arguments[0] || '1.0'+")";
document.body.style.webkitTransform = scaleVal;
}
);
console.log("rendering:" + destinations[pageindex]);
page.render(destinations[pageindex]); // RENDER PAGE //
if (pageindex == 0){
var loginInterval = setInterval(function() {
if (!loginInProgress && typeof loginSteps[loginIndex] == "function") {
console.log("login step: " + loginIndex )
loginSteps[loginIndex]();
loginIndex++;
}
if (typeof loginSteps[loginIndex] != "function") {
console.log("stopping login interval");
clearInterval(loginInterval);
console.log("starting page interval");
setInterval(LoadPage, 500);
}
}, 50);
}
pageindex++;
}
Turns out the problem was form submit vs button click. working code below:
var urlsLocation = "C:\\PhantomJs\\urls.txt";
var newScreenshotFolder = "C:\\PhantomJs\\NewScreenShot\\";
var fs = require('fs'),
system = require('system');
var content = '',
f = null,
lines = null,
pages =null,
destinations = null,
eol = system.os.name == 'windows' ? "\r\n" : "\n";
//read in a return separated list of urls
try {
f = fs.open(urlsLocation, "r");
content = f.read();
} catch (e) {
console.log(e);
}
if (f) {
f.close();
}
if (content) {
lines = content.split(eol);
pages = new Array();
destinations = new Array();
for (var i = 0, len = lines.length; i < len; i++) {
var pageName = lines[i].substring(lines[i].lastIndexOf('/') + 1);
pages[i] = pageName;
destinations[i] = newScreenshotFolder + pageName.replace(/[^a-zA-Z0-9\.]/g, "") + '.png';
}
}
console.log('Pages found: ' + pages.length);
var page = require('webpage').create();
var loginIndex = 0;
var loginInProgress = false;
var loginCompleted = false;
var loginSteps = [
function() {
//Enter Credentials
page.evaluate(function() {
document.getElementById("txtusername").value = "testemail#gmail.com";
document.getElementById("txtpassword").value = "12345678";
return;
});
},
function() {
//Login
page.evaluate(function() {
document.getElementById("btnLogin").click();
return;
});
}
];
var LoadPage = function() {
if (!loadInProgress && pageindex < pages.length) {
console.log("image " + (pageindex + 1) + " of " + lines.length);
page.open(lines[pageindex]);
}
if (pageindex == lines.length) {
console.log("<< Image render complete! >>");
phantom.exit();
}
}
//PNG RENDER
var pageindex = 0;
var loadInProgress = false;
var interval = setInterval(LoadPage, 500);
page.onLoadStarted = function() {
loadInProgress = true;
if(pageindex == 0) {
loginInProgress = true;
}
console.log('page ' + (pageindex + 1) + ' load started');
};
page.onLoadFinished = function() {
loadInProgress = false;
if(pageindex == 0)
{
loginInProgress = false;
console.log("stopping page interval");
clearInterval(interval);
}
page.evaluate(
function () {
var scaleVal = "scale("+arguments[0] || '1.0'+")";
document.body.style.webkitTransform = scaleVal;
}
);
console.log("rendering:" + destinations[pageindex]);
page.render(destinations[pageindex]); // RENDER PAGE //
if (pageindex == 0){
var loginInterval = setInterval(function() {
if (!loginInProgress && typeof loginSteps[loginIndex] == "function") {
console.log("login step: " + loginIndex )
loginSteps[loginIndex]();
loginIndex++;
}
if (typeof loginSteps[loginIndex] != "function") {
console.log("stopping login interval");
clearInterval(loginInterval);
console.log("starting page interval");
setInterval(LoadPage, 1000);
}
}, 50);
}
pageindex++;
}

Javascript prototype working

I have HTML application and someone wrote javascript library for that which is used for scrolling. Now i want to scroll to particular div with that library and i dont have to use location.href or `location.hash`` I have to do this with the JS library the code is something like this..
var ScrollPage = BGBiRepScroller.ScrollPage = function(){
this.animationFunList = [];
}
ScrollPage.prototype = {
$el:null,
$sectionList:null,
sectionPositionsY:null,
startTouchY:0,
startScrollY:0,
initTop:0,
endTouchY:0,
endDistance:0,
acceleration:8,
containerHeight:600,
currentSectionIndex:0,
isScrolling:false,
snapSection:true,
create: function($tEl){
this.$el = $tEl;
this.sectionPositionsY = new Array();
this.$sectionList = this.$el.find(".scrollSection");
var $origParent = this.$el.parent();
var $tempHolder = $("<div></div>");
$("body").append($tempHolder);
$tempHolder.css("opacity",0);
$tempHolder.append(this.$el);
this.$el.transition({ y: 0},0);
if(this.$sectionList.length>0){
this.initTop = this.$sectionList.position().top;
console.log("this.initTop::" + this.initTop);
for(var i=0; i<this.$sectionList.length; i++){
this.sectionPositionsY.push($(this.$sectionList[i]).position().top);
console.log($(this.$sectionList[i]).position().top);
}
}
$origParent.prepend(this.$el);
$tempHolder.remove();
this.createTouchEvents();
},
createTouchEvents: function(){
if(this.$el){
this.$el[0].ScrollPage = this;
this.$el.on(BGBiRep.Events.TOUCH_START, this._onTouchStart);
this.$el.on(BGBiRep.Events.TOUCH_END, this._onTouchEnd);
if(BGBiRep.isTouchDevice){
this.$el.on(BGBiRep.Events.TOUCH_MOVE, this._onTouchMove);
}
}
},
getSnapToY: function(_y){
var middleY = _y - this.containerHeight*.5;
if(this.snapSection){
for(var i=0; i<this.$sectionList.length; i++){
var $_currentEl = $(this.$sectionList[i]),
elTop = this.sectionPositionsY[i]-this.initTop;
if(-middleY<elTop){
//console.log('getSnapToY: middleY::' + middleY + ' ::elTop::' + elTop + ' ::this.initTop::' + this.initTop);
return 0;
}else if((-middleY>=elTop && -middleY<=elTop+$_currentEl.height()+10) || i==this.$sectionList.length-1){
//console.log("entering :: " + i);
this.currentSectionIndex = i;
if(i==0){return 0;}
return -(elTop - (this.containerHeight - $_currentEl.height())*.5);
}
}
}else{
console.log('_y::' + _y);
if(_y<-this.$el.find(".col1").height() + 550){
return -this.$el.find(".col1").height()+550;
}else if(_y>0){
return 0;
}else{
return _y;
}
}
return 0;
},
addAnimation: function(_sectionName, _function){
this.animationFunList.push(new Array(_sectionName, _function));
},
getAnimation: function(_sectionName){
for(var i=0; i<this.animationFunList.length; i++){
if(this.animationFunList[i][0] == _sectionName){
return this.animationFunList[i][1];
}
}
},
stopTransition: function(){
this.$el.css("transition", "transform 0s");
this.$el.css("-webkit-transition", "transform 0s");
},
_onTouchStart: function(event, touch){
var touch ;
this.ScrollPage.isScrolling = true;
if(BGBiRep.isTouchDevice){
touch = event.originalEvent.touches[0] || event.originalEvent.changedTouches[0];
}
var transformY = parseFloat(String(this.ScrollPage.$el.css('translate')).split(',')[1]) ;
this.ScrollPage.startTouchY = this.ScrollPage.endTouchY = (BGBiRep.isTouchDevice) ? touch.pageY : event.pageY;
this.ScrollPage.startScrollY = transformY;
if(!BGBiRep.isTouchDevice){
this.ScrollPage.$el.on(BGBiRep.Events.TOUCH_MOVE, this.ScrollPage._onTouchMove);
}
this.ScrollPage.stopTransition();
//this.ScrollPage.$el.css('-webkit-transition', '');
//this.ScrollPage.$el.css('transition', '');
},
_onTouchMove: function(event){
event.preventDefault();
var touch ;
this.ScrollPage.isScrolling = true;
if(BGBiRep.isTouchDevice){
touch = event.originalEvent.targetTouches[0];
}
var tY = (BGBiRep.isTouchDevice) ? touch.pageY : event.pageY;
var transY = this.ScrollPage.startScrollY - (this.ScrollPage.startTouchY - tY);
var maxY = (this.ScrollPage.snapSection)?(-this.ScrollPage.sectionPositionsY[this.ScrollPage.$sectionList.length-1]+this.ScrollPage.initTop):-this.ScrollPage.$el.find(".col1").height() + 580;
if(this.ScrollPage.currentSectionIndex == 0 && transY>0){
transY=0;
}else if(this.ScrollPage.currentSectionIndex == this.ScrollPage.$sectionList.length-1 && transY<maxY){
transY = maxY;
}else if(!this.ScrollPage.snapSection && transY<maxY){
transY = maxY;
}
this.ScrollPage.$el.transition({ y: transY},0);
this.ScrollPage.endDistance = this.ScrollPage.endTouchY-tY;
this.ScrollPage.endTouchY = tY;
},
_onTouchEnd: function(event, touch){
if(!BGBiRep.isTouchDevice){
this.ScrollPage.$el.off(BGBiRep.Events.TOUCH_MOVE, this.ScrollPage._onTouchMove);
}
if(this.ScrollPage.isScrolling){
var newY = this.ScrollPage.startScrollY - (this.ScrollPage.startTouchY - this.ScrollPage.endTouchY) - this.ScrollPage.endDistance*this.ScrollPage.acceleration;
console.log("newY::" + newY + "::" + this.ScrollPage.startScrollY + "-" + (this.ScrollPage.startTouchY - this.ScrollPage.endTouchY) + "-" +this.ScrollPage.endDistance*this.ScrollPage.acceleration);
this.ScrollPage.startScrollY = this.ScrollPage.startTouchY = this.ScrollPage.endTouchY = this.ScrollPage.endDistance=0;
//console.log("newY::-310::" + this.ScrollPage.getSnapToY(-310));
var tSCCROLL = this.ScrollPage;
this.ScrollPage.$el.css('-webkit-transition', '');
this.ScrollPage.$el.css('transition', '');
var tSnap =this.ScrollPage.getSnapToY(newY);
var transformY = parseFloat(String(this.ScrollPage.$el.css('translate')).split(',')[1]) ;
console.log('tSCCROLL.currentSectionIndex ' +tSCCROLL.currentSectionIndex);
var tFun = function(){
var tDid = $(tSCCROLL.$sectionList[tSCCROLL.currentSectionIndex]).attr("data-id");
console.log('inside tFun');
if(tDid && tDid!=''){
console.log('inside tDid');
tSCCROLL.getAnimation(tDid)();
console.log(tSCCROLL.getAnimation(tDid));
}
}
if(tSnap!=transformY){
tFun();
this.ScrollPage.$el.transition({ y: tSnap}, tFun);
}
}
this.ScrollPage.isScrolling = false;
}
}
There are section of div now on click i want to move to a particular section
$('.purple li').click(function(e)
{
//SOMETHING
});
How could i achieve this please someone help

Categories

Resources