How to open a link in the first open new browser tab - javascript

I know that this might not be possible.
Lets say I have a list of say 50 hyperlinks. The default behavior is to open the links in a new tab when clicked. But I want to prevent the user from opening 50 tabs if he/she clicks on all 50.
So is there any way to create a hyperlink which when clicked,
Opens the first link in a new tab
Subsequent links are opened in that same tab(instead of a new tab)
If it helps, Chrome will be the browser that we would use for this.
Is there any HTML.JS, Chrome trick that we can use? Thanks.

Add this snippet to your code, and check.
var a = document.getElementsByTagName("a");
for (i=0;i<a.length;i++) {
if (a[i].target="_blank") {
a[i].target="_self"
}
}

This works because it changes the URL of one window if it is opened to the link that the user clicked.
<html>
<head>
<title>
Search Engines
</title>
<script>
opened = false ;
function openMyLink(linkToOpen) {
if (opened === false) {
openWindow = window.open(linkToOpen,"_blank") ;
opened = true ;
openWindow.addEventListener("beforeunload",function () {opened = false ;}) ;
}
else {
openWindow.location.href = linkToOpen ;
}
}
</script>
<style>
a {
cursor : pointer ;
color : blue ;
text-decoration : underline ;
}
</style>
</head>
<body>
<h1>
Search Engines
</h1>
<br><a onclick="openMyLink('http://www.google.com/') ;">Google</a>
<br><a onclick="openMyLink('http://www.bing.com/') ;">Bing</a>
<br><a onclick="openMyLink('http://www.yahoo.com/') ;">Yahoo</a>
</body>
</html>

Related

Body onclick consecutive links

Hi I have this script that opens a new tab when clicking anywhere on the page but it works with only one link, I would like to make it so it can open links multiple times, consecutively. I would really appreciate any help.
<script type='text/javascript'>
var popup = function() {
window.open ("https://example.com/", "Window","status=1,toolbar=1,width=500,height=500,resizable=yes");
}
</script>
<body onclick='popup();'>
I tried multiples onclick in the body tag but it didn't work
If you want to cycle through multiple URLs, try this out.
<!DOCTYPE html>
<html>
<body onclick='popup();'>
<script>
const urls = ["https://www.google.com", "https://www.stackoverflow.com", "https://www.gmail.com"];
let counter = 0;
const popup = () => {
window.open(urls[counter++ % urls.length]);
}
</script>
</body>
</html>

javascript: open all links to pdf on a page in new window

I have a site that builds the pages dynamically. It's a SharePoint site. The site contains a lot of document libraries. The libraries contain word, excel and PDF documents. When a user clicks on a document, the document opens in the client application for office documents only. PDFs simply open in the same window. when people close the window containing the document, they close the site. I'm trying to use javascript to onload add target="_blank" to the PDF links.
So far I have:
window.onload = function(){
l=document.links.length;
for(i = 0; i<l; i++) {
n = document.links[i].href.indexOf(".pdf");
if (n > 0){
document.links[i].setAttribute('target', '_blank');
}
}
}
This code sort of works as some of the pdf links load in a new window as expected, some load in the parent window and some links load in both a new window and the parent. How do I tell the browser not to load in the parent window and only in the new window?
This is what I want to achieve:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
a.pdf<br /><br />
b.html<br /><br />
c.pdf<br /><br />
<script>
window.onload = function(){
l=document.links.length;
for(i = 0; i<l; i++) {
n = document.links[i].href.indexOf(".pdf");
if (n > 0){
document.links[i].setAttribute('target', '_blank');
}
}
}
</script>
</body>
</html>
The problem I'm running into is that sharepoint document libraries are modifying the link behavior such that the javascript does not make then open in a new window. Below is an example of a link from a document library:
<a onfocus="OnLink(this)" href="https://rcd.sharepoint.com/HR/HR%20Policy%20Manual.pdf" onmousedown="return VerifyHref(this,event,'0','','')" onclick="return DispEx(this,event,'TRUE','FALSE','FALSE','','0','','','','','331','0','0','0x7fffffffffffffff','','')">HR Policy Manual</a>
If you don't have access to all elements for ahead with capturing all clicks on the page. Use addEventListener with enabled capturing for handling event. Test whether it's anchor tag and proceed to new page by own with code below:
document.addEventListener("click", function(e){
if (e.target.localName == 'a') {
var url = e.target.getAttribute('href');
e.stopPropagation();
// You can place extra checks here.
var tab = window.open(url, '_blank');
tab.focus();
}
}, true)
Do
Here is what I would do, I think I would collect the anchors and loop over them to check if the hrefs ends with .pdf and then add a function on all the .pdf links
Don't
Don't check for pdf files with .indexOf('.pdf'). Your check should fail If there's a filename called somedummyfile.pdf.something.png (which is a .png image) or any other formatted file.
Note that, new window might be blocked at user's end if they are using add-blockers.
Here is the Snippet:
function modifyLinks() {
let links = document.getElementsByTagName('a');
let properties = 'height=' + window.innerHeight + ',width=' + window.innerWidth + ',' + 'scrollbars=yes,status=yes';
for (i = 0; i < links.length; i++) {
if (links[i].href.endsWith('.pdf')) {
// links[i].setAttribute('target', '_blank'); // if you want to open them in new tab;
console.log(links[i].href);
links[i].addEventListener('click', function(e) {
e.preventDefault();
window.open(this.href, '_blank', properties);
})
}
}
}
window.addEventListener('load', modifyLinks);
File 1
File 2
File 3
HTML Link
Some Other file
I added the following JavaScript to get links containing "pdf" to open in a new window:
window.onload = function(){
l=document.links.length;
for(i = 0; i<l; i++) {
n = document.links[i].href.indexOf(".pdf");
if (n > 0){
document.links[i].setAttribute('target', '_blank');
}
}
}
I then noticed that document libraries were using a DispEx() javascript function on click of document links which negated the first bit of code. I had to overload the function with my own functionality.
function DispEx(a){
if (a.href.endsWith('.pdf')){
window.open(a);
return false;
}
}
Using both pieces of JavaScript in a content editor web part, I got PDF documents to open in a new window and all other links/documents to load in the same window.

How to open a link in a new window and also in a new tab/window with right click?

I have a help link. If a user clicks on it, it opens a new window with fixed width and height. It's working well except that when I right click the link, there is either no options to 'open in a new tab' (in IE) or I can open in a new tab but is directed to an empty page (chrome). Can any one help to make this like a link and also by default open in a new window (not a tab)?
<html>
<head>
<title>
link
</title>
<script type="text/javascript">
function activateHelpView(helpUri) {
var WindowId = 'SomeWindowId';
var helpWindow = window.open(helpUri, WindowId, 'width=400,height=500,menubar=no,status=no,scrollbars=no,titlebar=no,toolbar=no,resizable=yes');
if (helpWindow) {
(helpWindow).focus();
}
}
</script>
</head>
<body>
<a id='PortOrderPageLearnMoreLink' href='javascript:' title='Learn more' onclick='activateHelpView("http://stackoverflow.com/")'>Learn more</a>
</body>
</html>
Use a real link, not the empty javascript: address. The onclick handler can prevent the link from doing anything "normal", but you'll have something for the right-click to work with.
target=_blank is a strong hint that you want the page opened in a new window, but whether that's honored at all -- and whether in a window or a tab -- is out of the page's control.
<script type="text/javascript">
function activateHelpView(helpUri) {
var WindowId = 'SomeWindowId';
var helpWindow = window.open(helpUri, WindowId, 'width=400,height=500,menubar=no,status=no,scrollbars=no,titlebar=no,toolbar=no,resizable=yes');
if (helpWindow) {
(helpWindow).focus();
}
}
</script>
<a id='PortOrderPageLearnMoreLink' href='http://stackoverflow.com/' title='Learn more' onclick='activateHelpView(this.href); return false;' target='_blank'>Learn more</a>
A more modern way of handling all of this -- particularly if there will be more than one help link -- is to add a class to all of them, and run some JavaScript to add the click handler to each in turn. The HTML stays clean (and with real links, still works if JavaScript is disabled or not loaded).
var helplinks = document.querySelectorAll('.helplink');
for (var i = 0; i < helplinks.length; ++i) {
helplinks[i].addEventListener('click', activateHelpView);
}
function activateHelpView(event) {
event.stopPropagation(); // don't let the click run its course
event.preventDefault();
var helpUri = this.href; // "this" will be the link that was clicked
var WindowId = 'SomeWindowId';
var helpWindow = window.open(helpUri, WindowId, 'width=400,height=500,menubar=no,status=no,scrollbars=no,titlebar=no,toolbar=no,resizable=yes');
if (helpWindow) {
helpWindow.focus();
}
}
<a id='PortOrderPageLearnMoreLink'
href='http://stackoverflow.com/' title='Learn more'
class='helplink' target='_blank'>Learn more</a>
StackOverflow snippets aren't allowed to use some of these functions. A working example can be found here.

How to open popup within a popup?

I want to open popup in another window open popup.
Please check code-
myjavascript.js
var win = null;
function NewWindow(mypage,myname,w,h,scroll){
LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
settings =
'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',resizable'
win = window.open(mypage,myname,settings)
}
index.html
<script src="myjavascript.js"></script>
My Account
popup1.html
<script src="myjavascript.js"></script>
Click to open popup2
popup2.html
<h1>You are now popup2.html page</h1>
Above code is working for me but the second popup not open. please check and let me know.
Thanks
#chatfun
The problem is that you're using the same identifier for both window.open(mypage,myname,settings).
Change the name in the second invocation:
index.html
My Account
popup1.html
Click to open popup2
Hope this helps,

close firefox tabs with javascript

I have a javascript code which opens a new tab in browser from a list each 50seconds, but the browser will crash after 50tabs or more.
so I want to close new tab and open another one each 50 seconds.
my code is:
<html>
<head>
<script>
function openWindow(){
window.open('"about:blank"');
var x = document.getElementById('a').value.split('\n');
atTime = 0;
for (var i = 0; i < x.length; i++) {
if (x[i].indexOf('.') > 0) {
site = x[i];
if (x[i].indexOf('://') < 0) { site = 'http://' + x[i]; }
setTimeout("window.open('" + site + "')", atTime);
atTime += 50000;
}
}
}
</script>
<style>
html, body
{
height : 99%;
width : 99%;
}
textarea
{
height : 80%;
width : 90%;
}
</style>
</head>
<body>
<textarea id="a"></textarea>
<br>
<input type="button" value="Open Windows" onClick="openWindow()">
<input type="button" value="Clear" onClick="document.getElementById('a').value=''">
</body>
</html>
window.open returns a reference to the new window. Call close on that handle.
https://developer.mozilla.org/en-US/docs/Web/API/window.close
note btw:
FAQ
How can I prevent the confirmation message asking the user whether he wants to close the window?
You can not. New windows not opened by javascript can not as a rule be closed by JavaScript. The JavaScript Console in Mozilla-based browsers will report the warning message: "Scripts may not close windows that were not opened by script." Otherwise the history of URLs visited during the browser session would be lost.
window.close() should work to close tabs you opened (but it's not possible to close a tab you didn't open)
in fact it can't be closed unless it was opened by a script but there is a way to fool the browser into thinking that's the case:
window.open('','_parent','');
then you can use
window.close();
Putting it together:
<script language="javascript" type="text/javascript">
function closeWindow() {
window.open('','_parent','');
window.close();
}
</script>
reference: http://www.yournewdesigner.com/css-experiments/javascript-window-close-firefox.html
to close a firefox tab use
window.close()
this will close the current window.

Categories