How to open a link in new tab using javascript - c#

I am working on a website, in which I have to open a url from backend. I am using c# now. My problem is that I want to open link in new tab instead of new window.
My code is here:-
string url = ppHref.ToString();
string newScript = "<script language='javascript'>window.open('" + ppHref.ToString() + "', '_blank');</script>";
ClientScript.RegisterStartupScript(this.GetType(),"OpenUrl", newScript);
Can Anybody tell me how to open this url in new tab. I don't like pop ups so I don't wanna use window.open(). Please help me.
Thanks in Advance

Sample Code

You can use:
window.open(url,'_target')
_target opens the page in next tab.

Html Code :
<button onclick="OpenInNewTab();" type="submit">
Javascript Code :
function OpenInNewTab(url) {
var win = window.open(url, '_blank');
win.focus();
}
Change Your Browser Setting.
In FireFox ,
Go To Options -> Tab setting and Check "Open New Windows in a New Tab instead" setting.
This Solution Worked For me .

I think answer to this question will help , Open a URL in a new tab using JavaScript https://stackoverflow.com/a/30512485/2293686
try like this,
$('#myButton').click(function () {
var redirectWindow = window.open('url', '_blank');
redirectWindow.location;
});

Related

Failed to locate element bind to an iframe

I am trying to automate login of following site:
https://www.sbs.com.au/ondemand/
after pressing Signin/Signup its opening login modal which is an iframe.
I am trying to locate email,password, login button with following code but not working. Its opening modal but after that doing nothing just test failing but no error message either.
Code for clicking Signin/signup link and switch to iframe:
var link = Driver.Instance.FindElement(By.Id("capture_signin_link"));
link.Click();
Driver.Instance.Manage().Timeouts().ImplicitWait.Seconds.Equals(10);
Driver.Instance.SwitchTo().Frame(1);
Code for passing value in email,password,and clicking login button:
var inputus = Driver.Instance.FindElement(By.Name("email"));
inputus.SendKeys(username);
Driver.Instance.Manage().Timeouts().ImplicitWait.Seconds.Equals(5);
var inputpass = Driver.Instance.FindElement(By.Name("password"));
inputpass.SendKeys(password);
Driver.Instance.Manage().Timeouts().ImplicitWait.Seconds.Equals(5);
var loginbutton = Driver.Instance.FindElement(By.ClassName("traditional-login"));
loginbutton.Click();
I am not sure if I am passing correct value to find locators and ifame. Please visit above site information for DOM info.
Looking forward a good solution. Please help me
My Latest Code for clicking signup to open login modal:
var link = Driver.Instance.FindElement(By.Id("capture_signin_link"));
link.Click();
Driver.Instance.Manage().Timeouts().ImplicitWait=TimeSpan.FromSeconds(10.00);
Driver.Instance.SwitchTo().Frame(Driver.Instance.FindElement(By.Id("login-iframe")));
Driver.Instance.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10.00);
Code for login:
IWebElement inputus = Driver.Instance.FindElement(By.XPath(".//*[#id='onboarding']/div[2]/form/section[2]/div/div[1]/input"));
inputus.SendKeys(username);
Driver.Instance.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10.00);
var inputpass = Driver.Instance.FindElement(By.Name("password"));
inputpass.SendKeys(password);
Driver.Instance.Manage().Timeouts().ImplicitWait=TimeSpan.FromSeconds(10.00);
var loginbutton = Driver.Instance.FindElement(By.ClassName("traditional-login"));
loginbutton.Click();
Above code worked for Chrome. On firefox its showing "Array out of index error" on Sendkeys() method. I found on some blog a lot of people are facing same problem and suggesting to downgrade firefox browser version to get proper support from getco driver as getco driver failing to handle sendkeys().
I haven't try above suggestion. Will try and update here. Till then if you have any other suggestion on that plz let me know.

WebCrawler click on a link not working when minimized

I have a crawler for this link:
http://www.ncbi.nlm.nih.gov/pubmed?term=Breast%20cancer%5BTitle%2FAbstract%5D
Unfortunately the links are handled by javascripts and there is no Href.
for this purpose I've created a crawler with a Web Browser component. I used this code to click on the link:
webBrowser1.Document.GetElementById("EntrezSystem2.PEntrez.PubMed.Pubmed_ResultsPanel.Entrez_Pager.Page").Parent.Children[3].Focus();
SendKeys.Send("{enter}");
but the problem is when I minimize the application, It can not click on the link because it can not focus. what should I do?
You can try to do this with JS:
var id = "EntrezSystem2.PEntrez.PubMed.Pubmed_ResultsPanel.Entrez_Pager.Page"
var script = "document.getElementById('{0}').parentNode.children[3].click()"
script = string.Format(script, id);
webBrowser1.Document.InvokeScript("eval", new object [] { script })
Additionally, I would advice to embed jQuery for better DOM navigation.

Executing client-side script on link click

I need my web page to open a window and enable a disabled button when a link or a button is clicked.
From what I've read on other posts on here, if I try and open a new window in Page_load most browsers will assume it's a pop-up and block it so I've been trying to do it client side with JS.
Currently, I'm trying it with a link declared like so:
Please click here to open the document.
This calls the following JS:
function OpenDoc()
{
<%= btnSubmit.ClientID %>.Visible = true;
Window.Open('GetDocument.aspx')
}
Unfortunately, instead of rending the JS as "btnSubmit.Visible = true" it comes out as "MainContent_btnSubmit.Visible = true" which doesn't work.
Assuming this is the best way of doing what I want, where am I going wrong?
You can't change visibility property through javascript but you can use the following code instead of it :
var control = document.getElementById('<%=btnSubmit.ClientID %>');
control.disabled = true;
In this case the button will be disabled and if you need to hide button not disableing it then use the following code :
var control = document.getElementById('<%=btnSubmit.ClientID %>');
control.style.display= "none";
Hope this is helpfull based on my understanding to your problem

ASP.NET MVC3: Split into two different Tabs

Form -> Submit
Takes you to view of the new entry.
How can I open a new tab that sends you to a new actionresult return File(document, mimeType); while still directing you on the main tab?
I'm at a loss, I cant open a new tab via ASP.NET Code, nor invoke two different actionresults.
Your problem should be solved on the client side, not only on the server. Maybe I misunderstood something, but if you want to open a new browser tab, you just need to place a <a href="#Html.Action("SomeAction")" target="_blank"> (Razor syntax) in your main tab.
You would need to do it client side. You have 2 options:
1) A shell page that has nothing except for the following javascript:
$(document).ready(function() {
window.open("#Model.DownloadUrl", "");
window.location.href = "#Model.RedirectUrl";
});
2) Modifying the view to check for a DownloadUrl via javascript and download it if available:
$(document).ready(function() {
if (#!string.IsNullOrEmpty(Model.DownloadUrl)) {
window.open("#Model.DownloadUrl", "");
}
});
In either case, there's no way to force the new window to be opened as a new tab. That's a user's browser setting. The javascript above opens a new tab in the version of Chrome and Firefox I have but not in IE.

How do I use Target=_blank on a response.redirect?

I do not necessarily have to use response.redirect, but that is what I had. I would like to open the selected link in a new window. How do I do that?
context.Response.Redirect(ConfigurationManager.AppSettings["URL"] + ext );
You can't is the short answer. The browser is the only thing that can open up a new window.
What you can do is send a chunk of html down the response that has a link with your url as an href, target="_blank" and a chunk of javascript onload of the form that fakes a click. If this doesn't work then use a window.open(url);
response.write("<script>");
response.write("window.open('page.html','_blank')");
response.write("</script>");
You're trying to accomplish a client-side task from the server side, so you'll need to do a bit of hacking.
One option is sending back a page that's just a bit of JavaScript, which then will handle the redirect.
This isn't particularly clean, but what about:
Response.Write("<script>window.open('http://www.somesite.com/','_blank');</script>");
Use the button's OnClientClick property:
<asp:Button runat="server" ID="cmd_Test" onclientclick="window.open('YourUrl')" />
If you are just handling navigation you can try a ASP:Hyperlink control rather than a button, that way the target is specified for the browser when the page is rendered:
protected void Page_Load (object sender, EventArgs e)
{
lnkViewPage.NavigateURL = sURL;
lnkViewPage.Target = "_blank";
}
Of course it is more polite to leave .Target alone because in this case the hyperlink could be right clicked and "open in new page/tab" would be available from the context menu.
You cannot do that with Response.Redirect()
Well you could do this using a simple Javascript inside Response.Write
Response.Write("<script>window.open('page.html','_blank')</script>");
SqlConnection con = new SqlConnection("Data Source=.; uid=sa; pwd=sandesh;database=BeautyJunction;");
string strSQL = "Select BenificiaryType,BenificiaryName,DisttCode,IFSC,AC_No from BenificiaryMaster";
SqlDataAdapter dt = new SqlDataAdapter(strSQL, con);
DataSet ds = new DataSet();
dt.Fill(ds, "UserDetail");
string dat = String.Format("{0: MM_dd_yyyy}", DateTime.Now);
//string dat = Convert.ToString(DateTime.UtcNow.ToShortDateString());
sb.Append("~/Folder1/BenificiaryMaster_file_1" + dat + ".xml");
string path = sb.ToString();
ds.WriteXml(Server.MapPath(path));
LabelMessage.Text = "Your XML file has Been created with name 'BenificiaryMaster_file_1" + dat +"' <a target='_blank' href=Folder1/BenificiaryMaster_file_1.xml>click here</a> to show Benificiary record file";
//GridView1.DataBind();
If I understand this correctly, you want to be able to open the redirected URL in a new window, but presumably retain the original target in the same window.
Unfortunately you cannot do this, because the redirect is served by the server and not browser. You could potentially redirect to a page that contained some script that opened a new window based on a URL querystring parameter. But this would open yourself up to XSS if your not careful.
How about a hyperlink that you program dymanically? Imagine this. asp hyperlink that when you click opens a new window, possibly with no scroll bars, no address bar, anything you want. Here is an example:
hyperlink1.Attributes.Add("onclick", "window.open(http://www.mylink.com?sessionvar1=" + someValue + "',null,'height=251px, width=600px,status=no, resizable=no, scrollbars=no, toolbar=no,location=no,menubar=no ');");
This is just an alternative to a standard button that would otherwise call a click handler. Keep in mind, you can add the whole thing from the front as an attribute.
I use this code for redirects:
Response.Write("window.open('http://www.whatever.com','_blank')<"+"/script>");
The final tag needs to be formatted <"+"/script>
I added to #DaveWalker response:
Response.Write("<script>")
Response.Write("window.open('NewPage.aspx','_blank','resizable=yes,scrollbars=yes,toolbar=yes,menubar=yes,location=no')")
Response.Write("</script>")
This will create a popup instead of opening a new tab.
I've seen many anwers and no one really works for me. So I tried the following code and it solved my problem:
First I changed mt button by a linkbutton with the same aspect as a button.
<asp:LinkButton ID="btPrint" runat="server" class="btn btn-primary"><span class="glyphicon glyphicon-print"></span> Print</asp:LinkButton>
After this I add the following in my code behind.
btPrint.Attributes.Add("href", String.Format("printPage.aspx?&id={0}", txtId.Text));
btPrint.Attributes.Add("target", "_blank");
This works for me
On aspx code:
<a id="myLink" target="_blank" onclick="window.open('ExamplePage.aspx, '_blank');">Link To A Page And Open Other Tab</a>

Categories

Resources