Saturday, April 18, 2020

Open Link in New Tab


All major browsers use popup blockers to prevent sites from opening new tabs. Popup blockers works in slightly different ways and block popups in different contexts.

First chapter gives short overview of popup blockers. The rest of article shows multiple ways how to open new tab and how to work around browsers limitations.

Table Of Contents

Popup Blockers

A browser does not distinguish between a new tab and a popup. Therefore popup blockers treat them the same way.
and in this article I use the terms "new tab" and "new window" interchangeably.

Popup blocker built inside the Firefox is willing to open new tab only from onclick hander. It prevents tab opening from mouse over event, network request response, and from inside script in the body. Instead of opening new tab, firefox will show yellow warning banner which says Firefox prevented this site from opening popup. It is possible to turn off the warning, but that requires user action.

Edge works similarly to Firefox, except that banner is white and show on bottom of the window.

Chrome always prevents new tabs from network request response. It mostly prevents also new tabs from on mouse over event and script inside the body. The last two are sometimes created, but I did not found when exactly. Chrome shows small icon in url bar when it refuses to open the new tab. User can click on it and allow popups manually.

Html Link

The easiest way to create a link that opens in a new tab is to add target="_blank" to it. It works in Chrome, Firefox and Edge.
<a href="http://gooogle.com" target="_blank">Normal Link</a>
This is how it renders: Normal Link

JavaScript

JavaScript can open new tab using the window.open(URL, name, specs, replace) function. The trick is to put '_blank' into name argument.
window.open('https://www.google.com', '_blank');
This works in most, but not all, situations. Most importantly, Edge and Firefox block new tab from network request response handler. When the url have to be loaded from backend, Firefox requires tricks to work.

This chapter has two sections. First section deals with situation when the frontend knows the url. Second section shows how to open link in new tab when the fronted needs to send network request.

When the Url is Known
In this chapter, we will try to open a new tab from mouse click, from timer, from mouse over and from a script inside the body.

From Click
Open new tab from onclick attribute of html tag works from Chrome, Firefox and Edge:
<a href="#" onclick="
    window.open('https://www.google.com', '_blank');
    return false;
">on click</a>
This is how it renders: on click

From Timer Inside Click
You can also start a timer while handling users onclick method and open a new tab later from the timer. It works in Chrome, Firefox and Edge:
<a href="#" onclick="
    setTimeout(() => window.open('https://www.google.com', '_blank'), 500);
    return false;
">click starts timer</a>
This is how it renders: click starts timer

From Mouse Over
Open new tab from onmouseover attribute of an html tag does not work. Firefox and Edge block it all the time. Chrome blocks it most of the time, although blocking is not perfect and the tab occasionally shows up:
<a href="#" onmouseover="
    window.open('https://www.google.com', '_blank');
    return false;
">on mouse over</a>
This is how it renders: on mouse over

From Timer Inside Mouse Over
Open new tab from timer started inside onmouseover does not work. Firefox and Edge block it all the time. Chrome blocks it most of the time, although blocking is not perfect and the tab shows up once in a while:
<a href="#" onmouseover="
setTimeout(function() {
 window.open('https://www.google.com', '_blank');
} ,500);
return false;
">timer on mouseover</a></br>
This is how it renders: timer on mouseover

From Body Onload
Opening new tab from script in body is blocked by all three browser. Add this inside the body tag to see it:
<script>
 console.log("installing");
 setTimeout(function() {
  console.log("running");
  window.open('https://www.google.com', '_blank');
 }, 500);
</script>

Fetching Url From Backend
More interesting and useful case is when the web application needs to fetch the url from backend. The straightforward solution does not work, Edge and Firefox block the new tab. However, this use case is too useful to be ignored, so we will build workaround.

From Request Response
Opening new tab from request response works only in Chrome. Edge and Firefox shows yellow warning and prevents new tab to open:
<script>
function fromHttpRequest() {
 const Http = new XMLHttpRequest();
 const url='https://jsonplaceholder.typicode.com/posts';
 Http.open("GET", url);
 Http.send();

 Http.onreadystatechange = (e) => {
   console.log(Http.responseText)
   window.open('https://www.google.com', '_blank');
 }
}
</script>
<a href="#" onclick="
    fromHttpRequest();
    return false;
">from http request</a></br>
This is how it renders: from http request

Starting timer from request response does not help. Chrome and Edge will open the tab, but Firefox will show warning instead. I have omitted the example, because it is long and almost the same as timers above.

Workaround 1
The workaround is to combine javascript interval started from user click, network request and let them communicate through variable.
  • Network request waits for response. Then it sets the common variable.
  • The interval periodically checks variable value. It opens new tab once the variable has the response. Then the interval removes itself.
<script>
function intervalListensForRequestResponse() {
 var iHaveTheResponse; // shared variable

 // send request
 const Http = new XMLHttpRequest();
 const url='https://jsonplaceholder.typicode.com/posts';
 Http.open("GET", url);
 Http.send();

 Http.onreadystatechange = (e) => {
   console.log(Http.responseText)
   iHaveTheResponse = 'https://www.google.com';
 }

 // periodically check the variable
 var refreshIntervalId = setInterval(function(){ 
    console.log('tick ' + iHaveTheResponse);
    if (iHaveTheResponse) {
     window.open(iHaveTheResponse, '_blank')
     clearInterval(refreshIntervalId);
    }
  }, 500);
 return false;
}
</script>
<a  href="#" onclick="
    return intervalListensForRequestResponse();
">interval listens for request response</a>
This is how it renders: interval listens for request response

Workaround 2
If the frontend knows for sure it will have to open new tab and just needs to acquire correct url from backend, you can:
  1. Open new window and keep reference to it.
  2. Send the request.
  3. Set url to newly opened window.

The disadvantage of this solution is that new window is opened before the response from backend came back. There is a blank window for few miliseconds. In addition, it is impossible to make backend decide whether the window will be needed or not.
<script>
function startByOpeningTheWindow() {
 var newTab = window.open("", '_blank');
 if (newTab==null) {
  return ;
 }


 // send request
 const Http = new XMLHttpRequest();
 const url='https://jsonplaceholder.typicode.com/posts';
 Http.open("GET", url);
 Http.send();

 Http.onreadystatechange = (e) => {
   console.log(Http.responseText);
   newTab.location.href = 'https://www.google.com';
 }
 return false;
}
</script>
<a href="#" 
      onclick="startByOpeningTheWindow();"
>first open the window, change url later</a></br>
This is how it renders: first open the window, change url later

Few Notes on Open Function
Communication between original window and new tab is possible if they have the same origin. If they show pages from different domains, the communication is blocked by the browser due to Same Origin Policy rules. It ends with Error: uncaught exception: Permission denied to get property error.

The window.open function returns reference to the tab that was just opened. The original page can use it to call functions inside newly opened tab. If the Firefox popup blocker blocked the popup, the function returns null. You can use this to check whether the new tab was blocked. This method works only for built-in popup blocker, it does not work for ad-blocking addons.

New tab has the opener property which can be used to call functions inside the main window. It also has the closed property. Main window can use it to check whether the child tab was open or not.

All Examples

All tested cases are on this page.

65 comments:

Siddharth said...

This is very good information I like this blog keep it up

Telegram Porn Channel || uk whatsapp group link 2020 || indian whatsapp group link 2020

KM PRATHAP REDDY said...

This is very good information I like this blog keep it up

delhi escorts said...

This is a good article, according to me, everyone should read this article and comment on it. I come to all the articles and try to learn something new.
delhi escorts
indian escorts
call girl


Unknown said...

nice article
CA IN INDIA
IB IN INDIA

phannhathoang144@gmail.com said...

Bài viết rất hay: Chúng tôi chuyên cung cấp các sản phẩm chất lượng



Lều xông hơi tại nhà giá rẻ



Lều xông hơi mua ở đâu



Lều xông hơi giá bao nhiêu

phannhathoang144@gmail.com said...

Bài viết rất hay: Chúng tôi chuyên cung cấp các sản phẩm chất lượng



Giảo cổ lam giảm mỡ hiệu quả



Tìm hiểu giảo cổ lam khô hiện nay



Tác dụng thần kỳ của giảo cổ lam khô

Unknown said...

After reading your article I was amazed. I know that you explain it very well
Android Training Institute in Coimbatore Best Android Training Institutes in Coimbatore | Android Training Course in Coimbatore | Mobile App Training Institute in Coimbatore | Android Training Institutes in Saravanampatti | Online Android Training Institutes in Coimbatore | Mobile Development Training Institute in Coimbatore

Unknown said...

Really useful information. Thank you so much for sharing

IOT Training in Coimbatore | Best IOT Training institute in Coimbatore | Internet of Things Course Training in Coimbatore | Best Institutes for IoT Internet of Things Training in Coimbatore | IOT Training Course in Coimbatore | IOT Training in saravanampatti

shanjeevani said...

Thank you so much for shearing this type of post.
This is very much helpful for me. Keep up for this type of good post.

thefranchisegroup said...

It's really nice and meaningful. it's really cool blog, Thank you. Franchise Opportunities .
Business Franchise Opportunities in India
Food Franchise Opportunity

Kailey Robinson said...

Download Video Player | Windows Media Player | Best Media Player

William said...

All the time I found something new information from your blogs. Thanks for sharing .hey... Great work . I feel nice while i reading blog .You are doing well. Keep it up. We will also provide QuickBooks Customer Service Contact us +1-855-756-1077 for instant help.

RGB Web Tech said...

Nice Blog ,your blog is sharing unique information....

We provide Web Design, Web Development, Digital Marketing (SEO, SEM, SMO, SMM), and Mobile App Development services.

* Web Design Services | Web Design Solutions
* Web Design Packages | Web Development Packages
* Technical SEO Checklist | Website Audit Checklist
* Online HTML Editor | Wysiwyg HTML Editor
* Career opportunities | Online Jobs From Home
* Web Designing Course | Free Online Courses with Certificates

For more information visit our website at Digital Marketing Services | Online Marketing Services

Reyansh said...

Useful for me.

up police bharti
cbse 10 maths sample paper

Rakesh said...
This comment has been removed by the author.
Rakesh said...

imaginative.ilmedu.org

Unknown said...

Your blog posts are more interesting and impressive. I think there are many people like and visit it regularly, including me. I appreciate your own position and I will be sure to come back here. embroidery digitizing

Phoebe Geller said...

Hey! Mind-blowing blog. Keep writing such beautiful blogs. In case you are struggling with issues on QuickBooks software, dial QuickBooks Customer Service Number The team, on the other end, will assist you with the best technical services.

MilesWeb said...

Are you looking for good hosting? So read Full Comparison of MilesWeb vs GoDaddy.

aditya said...

I read that Post and got it fine and informative.

garageband for pc
charles melton ethnicity
brooke simpson husband
pubfilm
Spy Dialer
free with edu email
aufbau principle

webseo said...

Immediately maintain a distance of 3 or 4 feet so that the electronics should not be a reason causing this error to you.

entertainmentbee.com
themoviesbio.com
petrefine.com

webseo said...

Is there an appropriate distance between your device and electronic devicesthepetsabout.com
happylifestyletrends.com
restaurantsnearme-opennow

webseo said...

Is it showing connect Epson printer to WiFi? Just relax there is nothing to be tensed for, it is just a very common issue and can be fixed easily.

frasesparaenamorarz.com
fras-es.com
punaisesdelit.org
groupe-sanguine.fr
meilleur-gps.fr

Zero Stock Brokerage said...

Thanks for sharing the important and awesome information, Thank you. How To Open Zerodha Account Opening Online , Zerodha Account Opening

thefranchisegroup said...

Your post was very nicely written, Thank you. Franchise Opportunities

Kailey Robinson said...

Thanks for the always useful information. This is great information to help peoples and nice article written by writer. CnX Player is a powerful & efficient 4K ultra HD enabled video player for Windows 10 PC & Tablet, Android and iOS – iPhone & iPad.

Download Media Player for Windows 10 - Microsoft Store
Download Video Player for Android from Google Play
Download Video Player for iPhone/iPad from Apple App Store

Parul Pathak said...

This site helps to clear your all query.
This is really worth reading. nice informative article.
vikram university bsc 3rd year result
vikram university pg result

CnX Player said...

Very nice and hepful post. CnX Player is a fantastic Video Player and offer a Casting feature that gives an absolute freedom to all its users to cast ANY (literally ANY) video format and ANY video codec from PC to TV within a fraction of seconds!

@CnXPlayer available on Windows 10, Android and iPhone/iPad

* Download Media Player from Windows 10 - Microsoft App Store
* Download Video Player from Android - Google Play
* Download Movie Player from iPhone/iPad -Apple App Store

For more information visit our website at Best Video Player

Delhi Escorts Service said...

Very Nice Post. Beautifull photos. Thanks for sharing. Contact @ +91-9818720667 Visit :

Best Escort Service Delhi
College Girl Escorts Service In Delhi
Escorts Service In Gurgaon
Escorts Service In Mahipalpur
Escorts Service In Karolbagh
Independent Escorts Service Noida
Escorts Service In Aerocity
Escorts Service In Connaught Place

Delhi Russian Escorts Service said...

Very intresting post. Like to see more from you.Beautiful pictures. Contact +91-9821283488 or visit us:

Escort service in Delhi
Gurgaon Escorts service
Mahipalpur Escorts service
Karolbagh Escorts service
Noida Escorts service
Saket Escorts service
Aerocity Escorts service
Greater Kailash Escorts service

North Carolina said...

Call us on Quickbooks Phone Number 1855-756-1077 to get targeted services

Minnesota said...

Our team at Quickbooks Phone Number1833-244-5865 is responsible to make sure that particular issue should be discarded in the quickest time. Here you will receive permanent solutions to QuickBooks issues.

Arizona said...

Get immediate assistance for QuickBooks errors on Quickbooks Phone Number1 877-948-5867.

Printersolution said...

Thank you so much for sharing this post, I appreciate your work.It was a great informative post. Go so many useful and informative links. Loved your writings also. Concept of the topic was well discussed. Love to come here again.
Printer solutions services

alexa jone said...

This is excellent information Thank you for sharing it is very helpful for .if you looking solution about accounting service then Dial at

:QuickBooks Customer Service +1 855-201-8294.our team always stand for help you at this difficult time

North Carolina said...

Fall back on a professional to solve quickbooks error 15215 for best service Quickbooks Phone Number 1 855-756-1077

Unknown said...

Reach to the customer service team via phone, emails, chat and get the best solution to the error occurred. Call us quickbooks customer service (888) 272-4881

Minnesota said...

If you have QuickBooks errors or problems that are slowing down your business? QuickBooks Customer Service Number is here to help. We have a team of experienced professionals who will be more than happy to solve any issue that you may have in the shortest time possible.
quickboks customer service(855) 742-7868.

emblixsolutions10 said...

EMBLIX is a leading Digital Marketing Company in Hyderabad offering a wide range of services including Digital Marketing, SEO, Social media marketing, Google AdWords, Facebook ads, and website designing. We offer comprehensive and customized services for our clients. Emblix as one of the best and top most service-oriented Digital Marketing Company in Hyderabad and India. One of the best SEO companies in Hyderabad, strive hard to provide all-encompassing digital marketing services along with web design and development. Emblix’s extensive market experience and expertise in Digital Marketing helps clients in successfully managing data as a strategic asset.

Unknown said...

The future of digital marketing is promising and full of possibilities.
As a result, skilled digital marketers who can keep up with the rising demand are in high order.

In the Emblix Academy Digital marketing institute in KPHB, you will learn about all the major and minor modules of digital marketing, from Search engine marketing to Social Media Marketing and almost all Tools used for Digital Marketing.

One stop place for all Digital Marketing courses! Emblix Academy is a Team of dedicated Professionals with 12years of experience in various Digital Platforms. We assure to provide the best Digital Marketing courses to enhance your Career.

https://emblixacademy.com/

Emblix solutions said...

EMBLIX is a leading Digital Marketing Agency in Hyderabad offering a wide range of services including Digital Marketing, SEO, Social media marketing, Google AdWords, Facebook ads, and website designing. We offer comprehensive and customized services for our clients. Emblix as one of the best and top most service-oriented Digital Marketing Company in Hyderabad and India. One of the best SEO companies in Hyderabad, strive hard to provide all-encompassing digital marketing services along with web design and development. Emblix’s extensive market experience and expertise in Digital Marketing helps clients in successfully managing data as a strategic asset.

tanuhealthdoctor said...

I really enjoy reading of your article. I wanted to inform you that you have people like me who appreciate your work. Definitely a great post I would like to read this.
check here

Rahul said...

Excellent Post! Very helpful information and thanks for sharing.

Adhiban is an Investment Banking & Financial Services Company in Coimbatore that offers personalized Financial Services to Corporate Companies & Entrepreneurs to raise capital.

johnrick said...

News The technology sector changes rapidly. It seems like every day a new gadget is being made available to the public. For those "techies" interested in the latest and greatest technological information, a good tech news blog or website is a great way to stay informed.
Gaming In this contemporary world, it has become liable to access each and everything with modern technologies; therefore, gaming peripherals are the best gaming devices which comfort the gamers who love to play the ideal games with easy and accessible device to play their skills.
Your Business If you think about it you can see that the news media has been evolving for some time. Business news was once only available in a newspaper that changed when television arrived on the scene.
Techy It is very important to keep yourself updated as far as the technology is concerned. You should try to get your hands of the latest technology and gadgets as soon as they hit the market.
Out Reach Outreach Galaxy is a platform that merchandise guest posts only with no limitation to minimum guest posts or any SEO metrics. Further, there’s no evaluation for home page features or any other requirements
Cricket In the sports arena, peak performance in sports has always been a much sought after state by players and coaches of all levels. Whether the athletes are school boys soccer players or Olympians striving for their Gold medals, peak performance in sports has always attracted athletes and coaches alike.
Tutors Careme Tutor” is a web based platform founded in 2018 that connects an increasing number of teachers with students for private, home sessions in the Pakistan.

Jay said...

for best cbse board exam preparation, visit the following links...
cbse class 10 sample papers
cbse class 10 blueprint
cbse grading system

perry said...

Nice blog post for reading and Thanks for sharing the wonderful article
internship request letter | Internship completion letter | internship companies | internship resume objective | internship application letter | Internship with training | internship email | internship experience | What internship means | Internship acknowledgement

Thanu Sree said...

Excellent blog since I have visited is really awesome. The important thing is that in this blog content written clearly and understandable. The content of information is very informative. We are also providing the best services click on below links to visit our website.
Oracle Fusion HCM Training
Workday Training
Okta Training
Palo Alto Training
Adobe Analytics Training

Unknown said...

Digital Marketing Institute in KPHB, we address all major and minor aspects required for any student’s advancement in digital marketing. Clutch USA named our Digital Marketing Institute the best SEO firm.

The future of digital marketing is promising and full of possibilities.
As a result, skilled digital marketers who can keep up with the rising demand are in high order.

In the Emblix Academy Digital marketing institute in KPHB, you will learn about all the major and minor modules of digital marketing, from Search engine marketing to Social Media Marketing and almost all Tools used for Digital Marketing.


Website: Digital Marketing Institute in KPHB

Oliver said...

Servlogin is a leading website for comprehensive data and analysis on Harris Teeter Ess . On this site you'll find daily updates on the latest trends shaping today's market, as well as in-depth reports from team of expert analysts who have been tracking these stocks for years. We break down the deals so you can make an informed decision about your investment. If you are considering a purchase or an initial public offering of Harris Teeter Ess, then check out our special reports section.

evoseedbox said...


excellent blog its really helps students for their assignments. its quite resourceful article.
for all students on here we have an all assignment service to help you guys to complete their assignment.
WEB Designing Services in chandigarh

raj biswas said...

your article so amazing and informative. Your writing skill is also very well. Your article is really addictive. Keep posting. keep sharing the knowledge. I love to read your articles.
english stories english short stories with moral value What is the factorial of 100

Sunny mohiy said...

Thank you for this very helpful guide on how to comment.

If you searching for a legit financial service .Check it out. Link below.
Buy a card
Unclaimed Mystery Box
legit PayPal transfer dark web
dark web financial services .

This will be very helpful for those you are just starting to blog...

AJ said...

I am very very impressed with your blog, I hope you will have more blogs or more articles to bring to readers. You are doing a very good job.

B.B.A 1st 2nd 3rd year exam date sheet

logesh said...

Interesting post!!! Thanks for posting such a useful information. I wish to read your upcoming post to enhance my skill set and keep blogging.
ibm full form in india |
ssb ka full form |
what is the full form of dp |
full form of brics |
gnm nursing full form |
full form of bce |
full form of php |
bhim full form |
nota full form in india |
apec full form

kaashivit said...

This is a great post. I like this topic.This site has lots of advantage.I found many interesting things from this site. It helps me in many ways.Thanks for posting this again.
eniac full form in computer
dvd full form
sit full form
pcc full form
iucn full form
full form of lcd
brics full form
tally erp full form
full form of ctbt
crpf full form

Surya Digital Marketing said...

Corporate Digital Marketing Training in Hyderabad
Comprehensive experience of association with 100+ corporates globally. Highly exclusive and bespoke training problems starting from the entry-level and varying to leadership levels. We are providing corporate digital marketing training in Hyderabad for the last many years and have created a significant presence as a corporate digital marketing training company.
Our Way of Corporate Training
Over the last few years, the evolution of the internet and its applications has reported an immense adaption amongst the people. The digital transformation has just created an upside change in the way the businesses used to operate earlier. It has fundamentally shifted the focus of companies towards new and improved ways of operating the business. In this new era of digitization, any business that denies going with this trend may get disrupted within the next few years. The corporate digital marketing training in Hyderabad has helped many companies and business ventures to upscale their business and help them achieve exponential growth. cOur training model is strategically designed and developed to inhibit businesses get the most profound and right amount of knowledge that helps them to upscale their business. We intend to provide any business the source of training that helps them to make a profitable source of revenue with the help of our training.

So let’s get a brief insight into our role and the strategies that we focus upon to upscale any business. We work on a 5 step methodology that is quite simple but extremely effective in creating a digital presence for the company.
https://www.emblixsolutions.com/

Mounika Digital Blogs said...

Digital marketing institute in KPHB Digital marketing institute in KPHB we address all major and minor aspects required for any student’s advancement in digital marketing. Clutch USA named our Digital Marketing Institute the best SEO firm.
The future of digital marketing is promising and full of possibilities.
As a result, skilled digital marketers who can keep up with the rising demand are in high order.
In the Emblix Academy Digital marketing institute in KPHB, you will learn about all the major and minor modules of digital marketing, from Search engine marketing to Social Media Marketing and almost all Tools used for Digital Marketing.
One stop place for all Digital Marketing courses! Emblix Academy is a Team of dedicated Professionals with 12years of experience in various Digital Platforms. We assure to provide the best Digital Marketing courses to enhance your Career.
Certifications
• Search Advertising
• Display Advertising
• Analytics Certification
• Hubspot Certification
• Bing Certification
• Twitter Certification
• Facebook Certification

kaashivit said...

Such a very useful blog. Very interesting to read this blog. I would like to thank you for the efforts you had made for writing this awesome blog.
eniac full form in computer
dvd full form
sit full form
pcc full form
iucn full form
full form of lcd
brics full form
tally erp full form
full form of ctbt
crpf full form

Emblixacademy said...

Digital Marketing Institute in KPHB Thanks for sharing such an interesting article. People should know this type of information to run in the flow and be present about what's going on in the market

hi said...

Amazing blog. Great share of information. Very useful
best c online course
online oracle
c course
cheap website design in chennai
big data training online

indian army said...

Indian Army GD Result
Indian Army Result
Indian Army GD Sample Papers
Indian Army Admit Card Download
Indian Army Bharti Selection Process
Indian Army Physical Eligibilty

pjskworks said...


Emblix Academy is today known as the best Digital Marketing Academy in Hyderabad which provides the student with a holistic learning experience throughout the course. Social media plays a vital role in deciding the consumer behavior towards Companies.

Amit Import said...

Import Globals is one of the leading import export data provider for India, Brazil, USA, and Kenya. For more information visit our website.
India Import Data

총판안마 총판안마 said...

조조안마
심심안마
총판안마
뷰티안마
카오스안마
꿀민안마
다이아안마
신라안마

사천출장샵 고성출장샵 said...

울산콜걸
경주콜걸
여수콜걸
이천콜걸










향남콜걸

Post a Comment