the screenshot is not getting displayed in phantomjs - javascript

I'am trying to get the high quality screenshot of the webpage.But it is not displaying the screenshot.Only the portion of the webpage is getting displayed.when i try to get the screenshot which doesn't need any cookie it is giving the screenshot properly but when i try using cookie it displays nothing(only a very very small portion is getting displayed).
This is how i have written my code.
'use strict';
var page = require('webpage').create(),
system = require('system'),
address, output, pixelRatio, width, height;
page.cookiesEnabled = true;
//i have added some of the cookies here which my page requires to load
var args = Array.prototype.slice.call(system.args, 1);
address = 'myurl';
output = 'd:/screenshots/11.png';
pixelRatio = 2;
page.onConsoleMessage = function(msg) {
console.log(msg);
};
// Here we block the first (few) requests until we have set the correct window variables
var resources = [];
page.onResourceRequested = function(requestData, networkRequest) {
if((requestData.url.match(/\.js/g) !== null || requestData.url.match(/\/js\//g) !== null)) {
if(requestData.url.match(/_phantomLoadMe/g) === null && requestData.url.match(/typekit/gi) === null) {
console.log('Temporarily blocking too soon request to ', requestData['url']);
resources.push(requestData['url']);
networkRequest.abort();
}
}
var reqUrl = requestData.url;
var newUrl = requestData.url.split(',%20')[0];
if (newUrl != reqUrl) {
networkRequest.changeUrl(newUrl);
}
};
width = (1440*pixelRatio);
height = (900*pixelRatio);
page.viewportSize = { width: width, height: height };
page.settings.localToRemoteUrlAccessEnabled = true;
page.settings.userAgent = 'Chrome/55.0.2883.87 Mozilla/5.0 (Windows NT 5.1; rv:8.0) Gecko/20100101 Firefox/7.0';
page.open(address, function (status) {
if (status !== 'success') {
console.log('Unable to load the address!', address, status);
phantom.exit();
} else {
// Manipulate the DOM
page.evaluate(function (r, urls, width, height) {
console.log('Setting window.devicePixelRatio to ' + r);
window.devicePixelRatio = r;
window.onload = false;
window.innerWidth = (width/r);
window.innerHeight = (height/r);
document.documentElement.offsetWidth = (document.documentElement.offsetWidth/r);
document.documentElement.offsetHeight = (document.documentElement.offsetHeight/r);
document.documentElement.clientWidth = (document.documentElement.clientWidth/r);
document.documentElement.clientHeight = (document.documentElement.clientHeight/r);
screen.width = width;
screen.height = height;
document.body.style.webkitTransform = "scale(" + r + ")";
document.body.style.webkitTransformOrigin = "0% 0%";
document.body.style.width = (100 / r) + "%";
// Now that we've set our window, let's get those scripts again
var _phantomReexecute = [];
var _phantomScripts = document.getElementsByTagName("script");
_phantomScripts = Array.prototype.slice.call(_phantomScripts);
if(_phantomScripts.length > 0) {
_phantomScripts.forEach(function(v) {
if('src' in v && v.src !== "" && v.src.match(/typekit/gi) === null) {
urls.push(v.src);
}
else {
_phantomReexecute.push({'script': v.innerHTML});
}
});
}
var _phantomAll = document.getElementsByTagName("script");
for (var _phantomIndex = _phantomAll.length - 1; _phantomIndex >= 0; _phantomIndex--) {
if(_phantomAll[_phantomIndex].src.match(/typekit/gi) === null) {
_phantomAll[_phantomIndex].parentNode.removeChild(_phantomAll[_phantomIndex]);
}
}
var _phantomHead = document.getElementsByTagName("head")[0];
if(urls.length > 0) {
urls.forEach(function(u) {
var _phantomScript = document.createElement("script");
_phantomScript.type = "text/javascript";
_phantomScript.src = u + '?_phantomLoadMe';
_phantomHead.appendChild(_phantomScript);
});
}
if(_phantomReexecute.length > 0) {
_phantomReexecute.forEach(function(s) {
var _phantomScript = document.createElement("script");
_phantomScript.type = "text/javascript";
_phantomScript.innerHTML = s.script;
_phantomHead.appendChild(_phantomScript);
});
}
// Make sure to execute onload scripts
var _phantomCount = 0;
var _phantomIntVal = setInterval(function() {
if(window.onload !== false && window.onload !== null) {
window.onload();
clearInterval(_phantomIntVal);
}
_phantomCount++;
if(_phantomCount > 10) {
clearInterval(_phantomIntVal);
}
}, 100);
}, pixelRatio, resources, width, height);
// Make the screenshot
window.setTimeout(function () {
page.render(output);
page.release();
phantom.exit();
}, 500000);
}

Related

PhantomJS rendering empty image

I have some strange error with PhantomJS.
I have chart.js line chart, with modified line colors:
codepen
Chart.defaults.multicolorLine = Chart.defaults.line;
Chart.controllers.multicolorLine = Chart.controllers.line.extend({
draw: function(ease) {
var startIndex = 0;
var meta = this.getMeta();
var points = meta.data || [];
var colors = this.getDataset().colors;
var area = this.chart.chartArea;
var originalDatasets = meta.dataset._children.filter(function(data) {
return !isNaN(data._view.y);
});
function _setColor(newColor, meta) {
meta.dataset._view.borderColor = newColor;
}
if (!colors) {
Chart.controllers.line.prototype.draw.call(this, ease);
return;
}
for (var i = 2; i <= colors.length; i++) {
if (colors[i-1] !== colors[i]) {
_setColor(colors[i-1], meta);
meta.dataset._children = originalDatasets.slice(startIndex, i);
meta.dataset.draw();
startIndex = i - 1;
}
}
meta.dataset._children = originalDatasets.slice(startIndex);
meta.dataset.draw();
meta.dataset._children = originalDatasets;
points.forEach(function(point) {
point.draw(area);
});
}
});
It looks normal in usual browser
But when I tried to render it on PHP server (Yii2) with PhantomJS:
var webPage = require('webpage');
var page = webPage.create();
page.viewportSize = {width: 1920, height: 1080};
var url = '%url%';
page.open(url, function (status) {
if (status === 'success') {
window.setTimeout(function () {
page.render('%path%', {format: 'jpeg', quality: '90'});
phantom.exit();
}, 3000);
}
});
It gives back empty image
Any ideas?
Solution: Replace PhantomJS with puppeteer

canvas is distorting itself and moving (fabric.js)

I just need an advice on where to look at or where to start as right now I am confused. Not sure if this is CSS issue, javascript, or fabric.js
Problem:
- I am adding a background image to canvas and sometimes it behaves really strange. And canvas is distorting itself sometimes on click, sometimes on resize, sometimes just without doing nothing. But this does not happen always.
These are two videos with the issue:
https://jumpshare.com/v/4FU3xWjqk4h6j0OwqaFs (this is just without
doing nothing).
https://jumpshare.com/v/tBS7NJC5VgccWnIssETw (this is me clicking on canvas)
This is how I add an image to canvas (fetching url via API):
$scope.openBlob = function($event, imageURL) {
$rootScope.isLoading();
$rootScope.centerSpinner();
if ($rootScope.currentTab === 1) {
var upload_thumb = angular.element($event.target.parentElement);
var circular = angular.element('<md-progress-circular md-mode="indeterminate" id="circular-images" md-diameter="30" ng-show="isAlsoLoading"></md-progress-circular>');
$compile(circular)($scope);
upload_thumb.prepend(circular);
} else {
var upload_thumb = angular.element($event.target.parentElement);
var circular = angular.element('<md-progress-circular md-mode="indeterminate" id="circular-new-middle" md-diameter="30" ng-show="isAlsoLoading"></md-progress-circular>');
$compile(circular)($scope);
upload_thumb.prepend(circular);
}
$rootScope.isAlsoLoading = true;
$http({
method: "GET",
url: imageURL.full,
responseType: "blob"
}).then(
function(res) {
var reader = new FileReader();
reader.readAsDataURL(res.data);
reader.onload = function(e) {
canvas.loadMainImage(e.target.result);
$rootScope.started = true;
$rootScope.uploaded = true;
$rootScope.changeStyling();
};
},
function(res) {
console.log("For some reasons it failed to open", res);
});
if ($rootScope.currentTab === 1) {
$rootScope.$on('editor.mainImage.loaded', function() {
$rootScope.isAlsoLoading = false;
upload_thumb.find("#circular-images").remove();
$rootScope.resetFilters();
$rootScope.isNotLoading();
});
} else {
$rootScope.$on('editor.mainImage.loaded', function() {
$rootScope.isAlsoLoading = false;
upload_thumb.find("#circular-new-middle").remove();
$rootScope.resetFilters();
$rootScope.isNotLoading();
});
}
}
LoadMainImage function content:
loadMainImage: function(url, height, width, dontFit, callback) {
var object;
fabric.util.loadImage(url, function(img) {
//img.crossOrigin = 'anonymous';
object = new fabric.Image(img, canvas.imageStatic);
object.name = 'mainImage';
if (width && height) {
object.width = width;
object.height = height;
}
canvas.mainImage = object;
canvas.fabric.forEachObject(function(obj) {
console.log('image object', obj);
if (obj && obj.name == 'mainImage') {
canvas.fabric.remove(obj);
}
});
canvas.fabric.add(object);
object.top = -0.5;
object.left = -0.5;
object.moveTo(0);
canvas.fabric.setHeight(object.height);
canvas.fabric.setWidth(object.width);
canvas.original.height = object.height;
canvas.original.width = object.width;
$rootScope.canvaswidth = canvas.original.width;
$rootScope.canvasheight = canvas.original.height;
$rootScope.calculateImageType(canvas.original.width, canvas.original.height);
if ($rootScope.gridadded) {
$rootScope.removeGrid();
$rootScope.addGrid();
}
if (!dontFit) {
canvas.fitToScreen();
}
$rootScope.$apply(function() {
$rootScope.$emit('editor.mainImage.loaded');
});
if (callback) {
callback();
}
});
},
Fit to screen function:
$scope.fitToScreen = function () {
$scope.zoom = canvas.currentZoom * 100;
if (canvas.mainImage) {
var oWidth = canvas.mainImage.width,
oHeight = canvas.mainImage.height;
} else {
var oWidth = canvas.original.width,
oHeight = canvas.original.height;
}
var maxScale = Math.min(3582 / oHeight, 5731 / oWidth) * 100,
minScale = Math.min(141 / oHeight, 211 / oWidth) * 100;
$scope.maxScale = Math.ceil(maxScale);
$scope.minScale = Math.ceil(minScale);
canvas.zoom(canvas.currentZoom);
};
UPDATE: I am assuming that it might be scaling (zooming in and zooming out issue)

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++;
}

Popup window Maximize button

How to enable the maximize and restore button of the popup window using Javascript?
You have to open a popup like this:
window.open('url', 'windowname', 'location=0, status=0, resizable=1, scrollbars=1, width=400, height=400');
The trick is to make the window resizable. Search for the window.open() function documentation.
Using the code I pasted on the bottom, you can emulate these buttons by creating them in your website interface.
To maximise: save the current position with Namespace.outerPositionGet() and size with Namespace.outerSizeGet(), then do Namespace.outerPositionSet({left:0,top:0}) and Namespace.outerSizeSet({width:window.screen.availWidth, height:window.screen.availHeight}).
To restore: just set position and size which were saved when maximising.
var Namespace = (function() {
var N, W, framePosition, frameChrome, setFramePosition, setFrameChrome;
N = {};
W = window;
setFramePosition = function() {
var tmp0;
if (typeof framePosition !== 'undefined') {
return;
}
tmp0 = {
top : W.screenTop,
left : W.screenLeft
};
W.moveTo(tmp0.left, tmp0.top);
framePosition = {
top : tmp0.top - W.screenTop,
left : tmp0.left - W.screenLeft
};
W.moveTo(tmp0.left + framePosition.left, tmp0.top + framePosition.top);
};
setFrameChrome = function() {
var tmp0, tmp1;
if (typeof frameChrome !== 'undefined') {
return;
}
tmp0 = N.innerSizeGet();
W.resizeTo(tmp0.width, tmp0.height);
tmp1 = N.innerSizeGet();
frameChrome = {
width : tmp0.width - tmp1.width,
height : tmp0.height - tmp1.height
};
W.resizeTo(tmp0.width + tmp1.width, tmp0.height + tmp1.height);
};
N.outerPositionSet = function(position) {
W.moveTo(position.left, position.top);
};
N.outerPositionGet = function() {
if (typeof W.screenTop !== 'undefined') {
setFramePosition();
N.outerPositionGet = function() {
return {
top : W.screenTop + framePosition.top,
left : W.screenLeft + framePosition.left
};
};
} else if (typeof W.screenY !== 'undefined') {
N.outerPositionGet = function() {
return {
top : W.screenY,
left : W.screenX
};
};
} else {
N.outerPositionGet = function() {
return {
top : 0,
left : 0
};
};
}
return N.outerPositionGet();
};
N.outerSizeSet = function(size) {
W.resizeTo(size.width, size.height);
};
N.outerSizeGet = function() {
if (W.outerWidth) {
N.outerSizeGet = function() {
return {
width : W.outerWidth,
height : W.outerHeight
};
};
} else {
setFrameChrome();
N.outerSizeGet = function() {
var size;
size = N.innerSizeGet();
size.width += frameChrome.width;
size.height += frameChrome.height;
return size;
};
}
return N.outerSizeGet();
};
N.innerSizeSet = function(size) {
setFrameChrome();
N.innerSizeSet = function(size) {
W.resizeTo(size.width + frameChrome.width, size.height + frameChrome.height);
};
N.innerSizeSet(size);
};
N.innerSizeGet = function() {
if (typeof W.innerHeight === 'number') {
N.innerSizeGet = function() {
return {
width : W.innerWidth,
height : W.innerHeight
};
};
return N.innerSizeGet();
}
var isDocumentElementHeightOff, node;
isDocumentElementHeightOff = function() {
var div, r;
div = W.document.createElement('div');
div.style.height = "2500px";
W.document.body.insertBefore(div, W.document.body.firstChild);
r = W.document.documentElement.clientHeight > 2400;
W.document.body.removeChild(div);
return r;
};
if (typeof W.document.clientWidth === 'number') {
node = W.document;
} else if ((W.document.documentElement && W.document.documentElement.clientWidth === 0) || isDocumentElementHeightOff()) {
node = W.document.body;
} else if (W.document.documentElement.clientHeight > 0) {
node = W.document.documentElement;
}
N.innerSizeGet = function() {
return {
width : node.clientWidth,
height : node.clientHeight
};
};
return N.innerSizeGet();
};
return N;
})();
I'm assuming you're talking about the alert popup? This can't be done with standard JavaScript.
You best solution would be to try using some of the many popup solutions that have been developed for the various JavaScript frameworks (e.g. jQuery), and seeing if you can tailor this to your particular use.
try this also. its working for me...
window.open('fileURL','status=1,directories=1,menubar=0,toolbar=0,
scrollbars=1,titlebar=0,dialog=1)
You can't, sorry - at least, not universally. The popup is implementation-dependent and there aren't any standard JavaScript methods for controlling it in the manner you describe.

Categories

Resources