How to open target="_blank" full screen? - javascript

I am trying to open new page with full screen. Below size is the my screen resolution. Still I have to click on re-sizable button on the browser to expand it to full screen.
How do I open it fill screen without clicking on re-sizeble?
Helper.Redirect("resource.aspx", "_blank",
"menubar=0,scrollbars=1,width=1366,height=768,top=10")
Method
Public Shared Sub Redirect(url As String, target As String, windowFeatures As String)
Dim context As HttpContext = HttpContext.Current
If ([String].IsNullOrEmpty(target) OrElse target.Equals("_self", StringComparison.OrdinalIgnoreCase)) AndAlso [String].IsNullOrEmpty(windowFeatures) Then
context.Response.Redirect(url)
Else
Dim page As Page = DirectCast(context.Handler, Page)
If page Is Nothing Then
Throw New InvalidOperationException("Cannot redirect to new window outside Page context.")
End If
url = page.ResolveClientUrl(url)
Dim script As String
If Not [String].IsNullOrEmpty(windowFeatures) Then
script = "window.open(""{0}"", ""{1}"", ""{2}"");"
Else
script = "window.open(""{0}"", ""{1}"");"
End If
script = [String].Format(script, url, target, windowFeatures)
ScriptManager.RegisterStartupScript(page, GetType(Page), "Redirect", script, True)
End If
End Sub
I tried 'fullscreen=yes, scrollbars=yes,location=yes,resizable=yes' parameters. It did not work.

Try:
window.open('newWin.html','NewWindow','fullscreen=yes');
Source:
Here

I had this same problem is simples just change this
Dim script As String
If Not [String].IsNullOrEmpty(windowFeatures) Then
script = "window.open(""{0}"", ""{1}"", ""{2}"");"
Else
script = "window.open(""{0}"", ""{1}"");"
End If
For this:
if (!String.IsNullOrEmpty(windowFeatures))
{
script = #"var w = window.open(""{0}"", ""{1}"", ""{2}""); w.moveTo(0,0); w.resizeTo(screen.width,screen.height-40);";
}
else
{
script = #"var w = window.open(""{0}"", ""{1}""); w.moveTo(0,0); w.resizeTo(screen.width,screen.height-40);";
if you want to is just put the property resizeto and moveTo

Related

Selenium: Capture DOM Elements Image

I have an API to capture the image of a particular element in DOM and return them. For that, I have a list of WebElements which needs to be captured into a single webpage. For that same, I have found the solution here which works fine if an element is visible on the screen (no need to scroll down to see it).
driver.get(urltoconnect);
WebElement ele = getElement();
// Get entire page screenshot
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
BufferedImage fullImg = ImageIO.read(screenshot);
// Get the location of element on the page
Point point = ele.getLocation();
// Get width and height of the element
int eleWidth = ele.getSize().getWidth();
int eleHeight = ele.getSize().getHeight();
// Crop the entire page screenshot to get only element screenshot
BufferedImage eleScreenshot= fullImg.getSubimage(point.getX(), point.getY(), eleWidth, eleHeight);
ImageIO.write(eleScreenshot, "png", screenshot);
// Copy the element screenshot to disk
File screenshotLocation = new File("C:\\images\\GoogleLogo_screenshot.png");
FileUtils.copyFile(screenshot, screenshotLocation);
But the cases where I need to scroll down to see element results in java.awt.image.RasterFormatException: (y + height) is outside of Raster. So I have added this.
What I have tried
//All Results in java.awt.image.RasterFormatException: (y + height) is outside of Raster
//scroll the page until the mentioned element is visible on the current page.
js.executeScript("arguments[0].scrollIntoView();",element);
//This will scroll down the page by 450 pixel vertical
js.executeScript("window.scrollBy(0,450)");
//AShot
Screenshot fpScreenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(400)).takeScreenshot(driver);
ImageIO.write(fpScreenshot.getImage(),"png",new File("image.png"));
Question is how can I capture the Image of particular elements where some elements need to be scrolled. Please note that I have multiple elements with there By.id, By.name, By.xpath for multiple sources so I can't set fullImg.getSubimage(x,y,w,h) by y+100 or something as this might work for one webpage but not for others. Any Help will be appreciated.
System.setProperty("webdriver.chrome.driver", "F:\\chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("https://www.testing-whiz.com/demoscripts/basic-element.html");
WebElement ele = getElement();
// Get entire page screenshot
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
BufferedImage fullImg = ImageIO.read(screenshot);
// Get the location of element on the page
Point point = ele.getLocation();
// Get width and height of the element
int eleWidth = ele.getSize().getWidth();
int eleHeight = ele.getSize().getHeight();
// Crop the entire page screenshot to get only element screenshot
try {
BufferedImage eleScreenshot= fullImg.getSubimage(point.getX(), point.getY(), eleWidth, eleHeight);
ImageIO.write(eleScreenshot, "png", screenshot);
}catch (Exception e) {
js.executeScript("window.scrollBy(0,450)");
//point.getY() = 732 //From console y = 492.8000183105469 after scroll https://stackoverflow.com/a/38767558/10961238
//raster.getHeight() = 613
BufferedImage eleScreenshot= fullImg.getSubimage(point.getX(), point.getY(), eleWidth, eleHeight);
ImageIO.write(eleScreenshot, "png", screenshot);
}
// Copy the element screenshot to disk
File screenshotLocation = new File("F:\\Images\\1.png");
FileUtils.copyFile(screenshot, screenshotLocation);
Backend: Spring Boot (Java 11)
Frontend: Angular
WebElement extends TakesScreenshot, which means you can use getScreenshotAs on the WebElement directly. You can
public void takeElementScreenshot(WebElement element) {
driver.executeScript("arguments[0].scrollIntoView();", element);
File screenshot = ele.getScreenshotAs(OutputType.FILE);
//...
}
You can check if the element is in viewport before scrolling, but I don't think it's necessary, just scroll every time

How to make print of web page particular area contains with charts?

I have a problem with printing a chart.
I made a web page contains with some number of controls and one chart, using Microsoft chart control. The issue currently is affecting me in both IE 8 and Firefox 9.0.1
When I made a print by using JavaScript then it prints all controls which are contained in div, but the chart control is not showing on the print preview page which is in same div.
If you are using Microsoft Chart Controls you can try following code for printing :
public void PrintWebControl(Control ctrl, string Script)
{
StringWriter stringWrite = new StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
if (ctrl is WebControl)
{
Unit w = new Unit(100, UnitType.Percentage);
((WebControl)ctrl).Width = w;
}
Page pg = new Page();
pg.EnableEventValidation =false;
if (Script != string.Empty)
{
pg.ClientScript.RegisterStartupScript(pg.GetType(), "PrintJavaScript", Script);
}
HtmlForm frm = new HtmlForm();
pg.Controls.Add(frm);
frm.Attributes.Add("runat", "server");
frm.Controls.Add(ctrl);
pg.DesignerInitialize();
pg.RenderControl(htmlWrite);
string strHTML = stringWrite.ToString();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Write(strHTML);
HttpContext.Current.Response.Write("<script>window.print();</script>");
HttpContext.Current.Response.End();
}
Calling :
PrintWebControl(Panel1);
gets you the print of the required chart.

Why does my code open two windows?

I'm trying to open a .pdf file in separate tab/window. It's working, but it opens two windows to show the .pdf.The code I used is as follows.
LinkButton btn = (LinkButton)(sender);
string value = btn.CommandArgument;
imfImageFile = LocalStaticData.UniImageResult;
string path = imfImageFile.WindowsPath;
if (path != "")
{
Session["OpenPDFImage"] = path;
ScriptManager.RegisterStartupScript(Parent.Page, GetType(),
Guid.NewGuid().ToString(), "openPdf(\"../InvoiceReport.aspx\" );", true);
}
JavaScript:
function openPdf(href) {
window.open(href);
}
Ok so two issues - I think Emanuele Greco is right that it is being called twice in your page cycle. The second issue is that you are giving it a unique code every time. You should be putting in the same code (not Guid.NewGuid()) to make sure the script only gets added once.
E.g.
LinkButton btn = (LinkButton)(sender);
string value = btn.CommandArgument;
imfImageFile = LocalStaticData.UniImageResult;
string path = imfImageFile.WindowsPath;
if (path != "")
{
Session["OpenPDFImage"] = path;
ScriptManager.RegisterStartupScript(Parent.Page, GetType(),
"InvoiceReportPDFOpenScript", "openPdf(\"../InvoiceReport.aspx\" );", true);
}

How to replace old URL in javascript pop-up with new URL

I need help of getting this piece of code to work
1) I want to automatically start a media player when a pop-up is open, by changing is URL params, that the pop-up has
2) When the user clicks on on the link I want to replace the old URL with the one the new one clicked. Try using location.replace just ends up being a constant loop.
Not having much luck with the code can anyone help????
var vidlink = $('.link').attr('href');
var autoplay = $('.link:first').attr('href');
var myurl = window.location.href,
paramsStr = autoplay,
paramsObj = {};
var newUrl = $.param.querystring(myurl, paramsStr );
if(window.location.href != newUrl){
location.replace(newUrl);
}
$('.link').click(function(){
loadPlayer(vidlink);
});
Open Player
player another show <a href='?v=53&a=false' class='link'>Ep2</a>
try windowname.document.location = newURL (where windoname is the name of the pop-up)

Open window in JavaScript with HTML inserted

How would I open a new window in JavaScript and insert HTML data instead of just linking to an HTML file?
I would not recomend you to use document.write as others suggest, because if you will open such window twice your HTML will be duplicated 2 times (or more).
Use innerHTML instead
var win = window.open("", "Title", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=780,height=200,top="+(screen.height-400)+",left="+(screen.width-840));
win.document.body.innerHTML = "HTML";
You can use window.open to open a new window/tab(according to browser setting) in javascript.
By using document.write you can write HTML content to the opened window.
When you create a new window using open, it returns a reference to the new window, you can use that reference to write to the newly opened window via its document object.
Here is an example:
var newWin = open('url','windowName','height=300,width=300');
newWin.document.write('html to write...');
Here's how to do it with an HTML Blob, so that you have control over the entire HTML document:
https://codepen.io/trusktr/pen/mdeQbKG?editors=0010
This is the code, but StackOverflow blocks the window from being opened (see the codepen example instead):
const winHtml = `<!DOCTYPE html>
<html>
<head>
<title>Window with Blob</title>
</head>
<body>
<h1>Hello from the new window!</h1>
</body>
</html>`;
const winUrl = URL.createObjectURL(
new Blob([winHtml], { type: "text/html" })
);
const win = window.open(
winUrl,
"win",
`width=800,height=400,screenX=200,screenY=200`
);
You can open a new popup window by following code:
var myWindow = window.open("", "newWindow", "width=500,height=700");
//window.open('url','name','specs');
Afterwards, you can add HTML using both myWindow.document.write(); or myWindow.document.body.innerHTML = "HTML";
What I will recommend is that first you create a new html file with any name.
In this example I am using
newFile.html
And make sure to add all content in that file such as bootstrap cdn or jquery, means all the links and scripts. Then make a div with some id or use your body and give that a id. in this example I have given id="mainBody" to my newFile.html <body> tag
<body id="mainBody">
Then open this file using
<script>
var myWindow = window.open("newFile.html", "newWindow", "width=500,height=700");
</script>
And add whatever you want to add in your body tag. using following code
<script>
var myWindow = window.open("newFile.html","newWindow","width=500,height=700");
myWindow.onload = function(){
let content = "<button class='btn btn-primary' onclick='window.print();'>Confirm</button>";
myWindow.document.getElementById('mainBody').innerHTML = content;
}
myWindow.window.close();
</script>
it is as simple as that.
You can also create an "example.html" page which has your desired html and give that page's url as parameter to window.open
var url = '/example.html';
var myWindow = window.open(url, "", "width=800,height=600");
Use this one. It worked for me very perfect.
For New window:
new_window = window.open(URL.createObjectURL(new Blob([HTML_CONTENT], { type: "text/html" })))
for pop-up
new_window = window.open(URL.createObjectURL(new Blob([HTML_CONTENT], { type: "text/html" })),"width=800,height=600")
Replace HTML_CONTENT with your own HTML Code
Like:
new_window = window.open(URL.createObjectURL(new Blob(["<h1>Hello</h1>"], { type: "text/html" })))
if your window.open() & innerHTML works fine, ignore this answer.
following answer only focus on cross-origin access exception
#key-in_short,workaround:: [for cross-origin access exception]
when you exec code in main.html -- which tries to access file window_ImageGallery.html by using window.open() & innerHTML
for anyone who encounter cross-origin access exception
and you dont want to disable/mess_around_with Chrome security policy
-> you may use query string to transfer the html code data, as a workaround.
#details::
#problem-given_situation,#problem-arise_problem::
say you exec following simple window.open command as other answer suggested.
let window_Test = window.open('window_ImageGallery.html', 'Image Enlarged Window' + $(this).attr('src'), 'width=1000,height=800,top=50,left=50');
window_Test.document.body.innerHTML = 'aaaaaa';
you may encounter following cross-origin access exception
window_Test.document.body.innerHTML = 'aaaaaa'; // < Exception here
Uncaught DOMException: Blocked a frame with origin "null" from accessing a cross-origin frame.
=> #problem-solution-workaround::
you may use query string to transfer the html code data, as a workaround. <- Transfer data from one HTML file to another
#eg::
in your main.html
// #>> open ViewerJs in a new html window
eleJq_Img.click(function() {
// #>>> send some query string data -- a list of <img> tags, to the new html window
// #repeat: must use Query String to pass html code data, else you get `Uncaught DOMException: Blocked a frame with origin "null" from accessing a cross-origin frame.` (cross origin access issue)
let id_ThisImg = this.id;
let ind_ThisImg = this.getAttribute('data-index-img');
let url_file_html_window_ImageGallery = 'window_ImageGallery.html'
+ '?queryStr_html_ListOfImages=' + encodeURIComponent(html_ListOfImages)
+ '&queryStr_id_ThisImg=' + encodeURIComponent(id_ThisImg)
+ '&queryStr_ind_ThisImg=' + encodeURIComponent(ind_ThisImg);
// #>>> open ViewerJs in a new html window
let window_ImageGallery = window.open(url_file_html_window_ImageGallery, undefined, 'width=1000,height=800,top=50,left=50');
});
in your window_ImageGallery.html
window.onload = function () {
// #>> get parameter from URL
// #repeat: must use Query String to pass html code data, else you get `Uncaught DOMException: Blocked a frame with origin "null" from accessing a cross-origin frame.` (cross origin access issue)
// https://stackoverflow.com/questions/17502071/transfer-data-from-one-html-file-to-another
let data = getParamFromUrl();
let html_ListOfImages = decodeURIComponent(data.queryStr_html_ListOfImages);
let id_ThisImgThatOpenedTheHtmlWindow = decodeURIComponent(data.queryStr_id_ThisImg);
let ind_ThisImgThatOpenedTheHtmlWindow = decodeURIComponent(data.queryStr_ind_ThisImg);
// #>> add the Images to the list
document.getElementById('windowImageGallery_ContainerOfInsertedImages').innerHTML = html_ListOfImages;
// -------- do your stuff with the html code data
};
function getParamFromUrl() {
let url = document.location.href;
let params = url.split('?')[1].split('&');
let data = {};
let tmp;
for (let i = 0, l = params.length; i < l; i++) {
tmp = params[i].split('=');
data[tmp[0]] = tmp[1];
}
return data
}
#minor-note::
(seems) sometimes you may not get the cross-origin access exception
due to, if you modify the html of 'window_ImageGallery.html' in main.html before window_ImageGallery.html is loaded
above statement is based on my test
& another answer -- window.open: is it possible open a new window with modify its DOM
if you want to make sure to see that Exception,
you can try to wait until the opening html window finish loading, then continue execute your code
#eg::
use defer() <- Waiting for child window loading to complete
let window_ImageGallery = window.open('window_ImageGallery.html', undefined, 'width=1000,height=800,top=50,left=50');
window_ImageGallery.addEventListener("unload", function () {
defer(function (){
console.log(window_ImageGallery.document.body); // < Exception here
});
});
function defer (callback) {
var channel = new MessageChannel();
channel.port1.onmessage = function (e) {
callback();
};
channel.port2.postMessage(null);
}
or use sleep() with async What is the JavaScript version of sleep()?
eleJq_Img.click(async function() {
...
let window_Test = window.open( ...
...
await new Promise(r => setTimeout(r, 2000));
console.log(window_Test.document.body.innerHTML); // < Exception here
});
or you get null pointer exception
if you try to access elements in window_ImageGallery.html
#minor-comment::
There are too many similar Posts about the cross-origin issue. And there are some posts about window.open()
Idk which post is the best place to place the answer. And I picked here.

Categories