I have an image which when click, I want to link to a mailto:
<a id="mailto" href="mailto:hfms#live.com.my" target="_newtab" >
<img src="#Url.Content("~/Content/HomePage/email.png")" alt="email" /></a>
However, currently once its clicked, it will launch the email option to choose a mailto application, and once i choose, the mailto link is open in the current tab. This will cause user to leave the application.
So, I want the page to sent email (by gmail, yahoo, etc ) is either open in new tab or in a window. Any idea how to do this? I tried both target="_newtab" and target="_blank" but both didn't work.
Any help will be much appreciated.. Thanks...
(jQuery method is also acceptable if there is no other way, thanks)
this information is outdated, now it is possible to do so i believe, since gmail and others now work via browser links. there is however the problem that you would only want it to open in a new tab if NOT opening in a system mail client, and open in a new tab if it is a webmail client, otherwise for example Outlook users see a blank tab appear, which is disorienting, especially since they are Outlook users.
You don't need Javascript/Jquery for this. A standard link works (except Firefox v30+ due to a bug, see below).
<a href="mailto:example#example.com" target="_blank">
As of Firefox 30, does not work in Firefox due to a bug. It opens in the same tab AND replaces history so hitting back will not bring you back to the page where the mailto: link was.
This answer is based on this answer Open the href mailto link in new tab / window.
Right now, new browsers support some web mail interfaces (Like Gmail, Yahoo Mail, AoL, etc.).
So we can simply open a new window (Support older browser, new browsers just will open a new tab) and add a fallback (In case of non-javascript user) using preventDefault and default link redirection.
http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-flow-cancelation
https://developer.mozilla.org/es/docs/DOM/event.preventDefault
https://developer.mozilla.org/en-US/docs/Web/API/Window.open
Like so:
<a onClick="javascript:window.open('mailto:mail#domain.com', 'mail');event.preventDefault()" href="mailto:mail#domain.com">Send a e-mail</a>
http://jsfiddle.net/cNUNP/
Credit to https://stackoverflow.com/a/9880404/1107020
Guess that's all.
Greetings, Marcos.
mailto calls the users default email client. It does not open a window or tab in any instance. If you want to use a window or tab you need to configure a form and allow the form to open in your window/tab. Of course, you'll have to configure the form to send mail with whatever method is available on your server.
I know this is an old question, but this thread had the best set of answers if found. I modified Marcos's Answer above to also close the blank tab that is created if the client has an external mail handler
reference answer
JS (w\ jQuery for event handlers)
$(document).on('click', 'a[href^=mailto]', function(e) {
var checkClose, checkLoaded, event, href, i, len, loadEvents, results, t, wndw;
e.preventDefault();
href = this.href;
wndw = window.open(href, 'mail');
checkClose = function() {
console.log('checkClose');
try {
wndw.location.href;
return wndw.close();
} catch (error) {
return console.log('webmail');
}
};
t = setTimeout(checkClose, 5000);
try {
checkLoaded = function() {
console.log('loaded');
clearTimeout(t);
return t = setTimeout(checkClose, 2000);
};
wndw.onload = checkLoaded;
loadEvents = ["DomContentLoaded", "load", "beforeunload", "unload"];
results = [];
for (i = 0, len = loadEvents.length; i < len; i++) {
event = loadEvents[i];
results.push(wndw.addEventListener(event, checkLoaded));
}
return results;
} catch (error) {
return checkLoaded();
}
});
jsfiddle
Can confirm that '_blank' is still not working in Firefox for an emailto link. Instead use an onClick function that will do something like this:
window.open('mailto:'+email+'?subject='+subject);
Variant 1 (JavaScript):
<script>
// Open mailto links in a new tab
function mailto(email, subject, body) {
var url;
url = 'mailto:' + email;
url += '?subject=' + subject;
url += '&body=' + body;
window.open(url);
}
</script>
test#gmail.com
Variant 2 (JavaScript):
<script>
// Open mailto links in a new tab
function mailto(th) {
var url = th.getAttribute('href');
window.open(url);
}
</script>
test#gmail.com
Variant 3 (jQuery):
<script>
// Open mailto links in a new tab
$('#mailto').click(function (e) {
e.preventDefault();
var url = $(this).attr('href');
window.open(url);
});
</script>
test#gmail.com
Variant 4 (jQuery):
<script>
// Open mailto links in a new tab
$("a[href^='mailto:']").click(function(e) {
e.preventDefault();
var href = $(this).attr('href');
var target = $(this).attr('target');
window.open(href, target ? target : '_self');
});
</script>
test#gmail.com
HTML target Attribute: https://www.w3schools.com/tags/att_a_target.asp
Have you tried 'middle-click' ( "Open in new tab" ) ?
It works for me
(http://forums.mozillazine.org/viewtopic.php?f=7&t=1842595)
although it seems particularly strange to ask user to Middle click
Anyway I've found a pseudo solution that seems to work in FF 25/ Chrome 35
1.- Set up your link something like this:
<a href="javascript:void()"
class="mailToLink"
data-mail="mailaddr#domain.com">mailaddr#domain.com </a>
2.- Using javascript ( with jquery in the example) setup an onlclick event like:
$('.mailToLink').on('click', function(){
mailto=$(this).data('mail');
w=window.open('','_blank','',true);
w.location.href='mailto:'+mailto;
w.focus();
});
This opens a blank new window/tab and later changes its location, so the mail protocol handler is unable toto act until the new window is already opened
Not tested with Local mail client ( Outlook et al.)
There is a cheap html-hack to this problem.....
The link on one page...
Mail
On mailto.html....
<meta HTTP-EQUIV="REFRESH" content="0; url=mailto:who#website.com">
If nothing pops up click.....Mail!
_blank opens a new tab/window and the metatag does the rest. link as fallback offcourse.
Related
According to this solution I made a button that execute the href and it is not redirect me to the page (I'am developing an web application, when someone is clicking a button a http request is running and an application is opening), the problem is when I'am testing this from my tablet, when i touch the button it redirects me to the page and I don't know how to fix this.
// Act on clicks to a elements
$("#link1").on('click', function(e) {
// prevent the default action, in this case the following of a link
e.preventDefault();
// capture the href attribute of the a element
var url = $(this).attr('href');
// perform a get request using ajax to the captured href value
$.get(url, function() {
// success
});
});
<a id='link1' href="http://www.google.com">Link</a>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
If you don't want it to act like a normal link, I wouldn't use the href attribute but instead something more abstract like data-href for example. You can still get the attribute through jquery and won't have to prevent any defaults.
This is for asynchronous and not creating new tab
You should use # as href and add data-href
// Act on clicks to a elements
$("#link1").on('click', function(e) {
// prevent the default action, in this case the following of a link
e.preventDefault();
// capture the href attribute of the a element
var url = $(this).attr('data-href');
// perform a get request using ajax to the captured href value
$.get(url, function() {
// success
});
});
and the html
<a id='link1' href="#" data-href="http://www.google.com">Link</a>
This is for creating a new tab:
change the
$.get(url, function() {
// success
});
to
window.open(url).
(Question1, question2 and question3 looks how to force users open link in new tab)
But in my situation I visit some sites regularly and they have links like this:
<a href='javascript:window.open("/view.php?id=1234","_self")'>Link name</a>
This type of link makes me impossible to open link in new tab with a mouse click. Every time I see these links, I duplicate the tab in Chrome and click link inside the cloned tab. And go back to original tab and continue to surf. Is it possible to open these links in new tab with a chrome extension, js code or something?
You can try one of the links here: http://bit.ly/12dUk4V
. . The problem is that these links can be kind of "about:blank" because they are not specified in the href attribute normally, so it breaks your expected behavior when using ctrl+click, middle click or something alike. Sometimes sites links to "javascript:" pseudo-protocol, sometimes the link is for "#" with a "onclick" trigger... It depends on the situation.
. . For this specific case it's easy enough to write a user script that will rewrite these kind of links, if you're willing to use something like Tampermonkey:
// ==UserScript==
// #name SelfLinks Fixer
// #namespace http://dnun.es./
// #version 0.1
// #description This script rewrites "window.open(..., '_self')" links so that you can click them as you wish.
// #match http://libgen.info/*
// #copyright 2013, http://dnun.es.
// ==/UserScript==
var tRegExp = '^javascript: *'+
'(window\\.)?open\\('+
' *(([\'"])([^\\3]+)\\3) *,'+
' *[\'"]_self[\'"] *'+
'\\) *;? *$';
var fixLinksCheck = new RegExp(tRegExp);
var as = document.getElementsByTagName('a'), i = 0, n = as.length, a;
for (;i<n;i++) { a = as[i];
if (fixLinksCheck.test(a.href)) { //damn you _self link!
a.href = a.href.replace(fixLinksCheck, '$4');
}
}
. . This code "fixes" only the "_self" links by changing them to normal links. You can then click them with middle button, holding ctrl/shift or whatever. It also leave the "_blank" or "_top" links untouched.
Yes, it is possible. All you need is to inject a simple line of JavaScript code in every page. I had done it before in a Firefox extension.
You just need to override window.open method:
var open_= window.open;
window.open = function(url, name, opts) {
if (name === '_self') { name = '_blank'; }
open_(url, '_blank', opts);
};
Complete code on JsFiddle: http://jsfiddle.net/dp4Uz/
If the user clicks the link, then I would like to open a page in a new tab, and jump to #section on the parent site. How is it possible without JS?
This doesn't work:
html
<a href="#section">link</a>
AFAIK, you have to use JavaScript to request multiple URLs via the same anchor.
Some Text
With JavaScript, you would be able to watch for the onclick event to open a new window, like so:
document.getElementById("doubleLink").onclick = function() {
window.open("http://www.someothersite.com/");
}
Simply add #section to the address.
<a href="http://target_site#section">
I think you need to use javascript, but not much:
document.getElementById('myLinkId').addEventListener('click', function() {window.location = '#section'}, false);
EDIT: As far as I know, it can't be done without javascript. What would happen to a double link that didn't open a new tab?
I realize you may also need it to work in older IE.
var doubleLink = document.getElementById('myLinkId');
if (window.addEventListener) {
doubleLink.addEventListener('click', function() {window.location = '#section'}, false);
} else {
doubleLink.attachEvent('onclick', function() {window.location = '#section'});
}
Is there a way without Javascript / server-side scripting to link to a different port number on the same box, if I don't know the hostname?
e.g.:
Look at the other port
(This example does't work as it'll just treat :8080 as a string I want to navigate to)
How about these:
Modify the port number on click:
Look at another port
However, if you hover your mouse over the link, it doesn't show the link with new port number included. It's not until you click on it that it adds the port number. Also, if the user right-clicks on the link and does "Copy Link Location", they get the unmodified URL without the port number. So this isn't ideal.
Here is a method to change the URL just after the page loads, so hovering over the link or doing "Copy Link Location" will get the updated URL with the port number:
<html>
<head>
<script>
function setHref() {
document.getElementById('modify-me').href = window.location.protocol + "//" + window.location.hostname + ":8080/other/";
}
</script>
</head>
<body onload="setHref()">
Look at another port
</body>
</html>
You can do it easily using document.write and the URL will display correctly when you hover over it. You also do not need a unique ID using this method and it works with Chrome, FireFox and IE.
Since we are only referencing variables and not loading any external scripts, using document.write here will not impact the page load performance.
<script language="JavaScript">
document.write('<a href="' + window.location.protocol + '//' + window.location.hostname + ':8080' + window.location.pathname + '" >Link to same page on port 8080:</a> ' );
</script>
It would be nice if this could work, and I don't see why not because : is a reserved character for port separation inside the URI component, so the browser could realistically interpret this as a port relative to this URL, but unfortunately it doesn't and there's no way for it to do that.
You'll therefore need Javascript to do this;
// delegate event for performance, and save attaching a million events to each anchor
document.addEventListener('click', function(event) {
var target = event.target;
if (target.tagName.toLowerCase() == 'a')
{
var port = target.getAttribute('href').match(/^:(\d+)(.*)/);
if (port)
{
target.href = window.location.origin;
target.port = port[1];
}
}
}, false);
Tested in Firefox 4
Fiddle: http://jsfiddle.net/JtF39/79/
Update: Bug fixed for appending port to end of url and also added support for relative and absolute urls to be appended to the end:
Test absolute
Test relative
Modify the port number on mouseover:
Look at another port
This is an improvement of https://stackoverflow.com/a/13522508/1497139 which doesn't have the draw back of not showing the link correctly.
This solution looks cleaner to me
<a href="#"
onclick="window.open(`${window.location.hostname}:8080/someMurghiPlease`)">
Link to some other port on the same host
</a>
Without JavaScript, you'll have to rely on some server side scripting. For example, if you're using ASP, something like ...
Look at the other port
should work. However, the exact format will depend on the technology you are using.
After wrestling with this I found actually that SERVER_NAME is a reserved variable. So, if you are on page (www.example.com:8080) you should be able to drop the 8080 and invoke another port. For instance this modified code just worked for me and moves me from any base port to port 8069 (replace your port as required)
<div>
<a href="http://<?php print
$_SERVER{'SERVER_NAME'}; ?>:8069"><img
src="images/example.png"/>Example Base (http)</a>
</div>
It's better to get the url from the server variables:
// PHP:
<a href="<?=$_SERVER['SERVER_NAME']?>:8080/index.php">
// .net:
<a href='<%=Request.ServerVariables('SERVER_NAME')%>:8080/index.asp'>
No need of complicated javascript : simply insert a script node after your anchor, then get the node in javascript, and modify its href property with the window.location.origin method.
<a id="trans">Look at the other port</a>
<script>
document.getElementById('trans').href='http://'+window.location.origin+':8081';
</script>
The id property must be unique page wide, so you may want to use other method to retrieve node objects.
Tested with apache and Firefox on Linux.
Based on Gary Hole's answer, but changes urls on page load instead of on click.
I wanted to show the url using css:
a:after {
content: attr(href);
}
So I needed the anchor's href to be converted to contain the actual url that would be visited.
function fixPortUrls(){
var nodeArray = document.querySelectorAll('a[href]');
for (var i = 0; i < nodeArray.length; i++) {
var a = nodeArray[i];
// a -> e.g.: Test
var port = a.getAttribute('href').match(/^:(\d+)(.*)/);
//port -> ['8080','/test/blah']
if (port) {
a.href = port[2]; //a -> Test
a.port = port[1]; //a -> Test
}
}
}
Call the above function on page load.
or on one line:
function fixPortUrls(){var na=document.querySelectorAll('a[href]');for(var i=0;i<na.length;i++){var a=na[i];var u=a.getAttribute('href').match(/^:(\d+)(.*)/);u&&a.href=u[2]&&a.port=u[1];}}
(I'm using for instead of forEach so it works in IE7.)
None of the answers I looked at (and I will say, I didn't read them all) adjust the URL such that a middle click or "open in new tab" would function properly -- only a regular click to follow the link. I borrowed from Gary Greene's answer, and instead of adjusting the URL on-the-fly, we can adjust it when the page loads:
...
<script>
function rewriteRelativePortUrls() {
var links = document.getElementsByTagName("a");
for (var i=0,max=links.length; i<max; i++)
{
var port = links[i].getAttribute("href").match(/^:(\d+)(.*)/);
if (port)
{
newURL = window.location.origin + port[0]
links[i].setAttribute("href",newURL)
}
}
}
</script>
<body onload="rewriteRelativePortUrls()">
...
I also needed the same functionality, but I wanted to also do protocol replacement.
My solution will look for data-samehost-port or data-samehost-protocol and regenerate the href attribute on the anchor tag to use the same current hostname with the specified port and/or protocol.
Here is what I'm using:
...
<script type="text/JavaScript">
/**
In http you cannot make a relative link to the same domain but different port.
This script will take urls that look like this:
[given current url: 'http://some-domain.com:3000/a/path/file.html']
1. <a data-samehost-port="8080" href="/some/path">some link</a>
2. <a data-samehost-protocol="https" href="/some/path">some link</a>
3. <a data-samehost-protocol="https" data-samehost-port="8080" href="/some/path">some link</a>
and make them look like this:
1. some link
2. some link
3. some link
**/
document.addEventListener('DOMContentLoaded', function() {
[... new Set([].concat(
Array.from(document.querySelectorAll('[data-samehost-port]')),
Array.from(document.querySelectorAll('[data-samehost-protocol]'))
))]
Array.from(document.querySelectorAll('[data-samehost-port]')).forEach(e=>{
let port = '80'
let path = e.getAttribute('href')
const {hostname,protocol} = document.location
if(e.hasAttribute('data-samehost-protocol')){
protocol = e.getAttribute('data-samehost-protocol')
e.removeAttribute('data-samehost-protocol')
}
if(e.hasAttribute('data-samehost-port')){
port = e.getAttribute('data-samehost-port')
e.removeAttribute('data-samehost-port')
}
if(port==='80') port=''
e.href = `${protocol}//${hostname}${port?`:${port}`:''}${path}`
})
})
</script>
...
I have a html page A and a link in the page which opens up page B in a new window. How to reload the page A on clicking and opening this link ?
EDIT:
I should have been more clear. Page B opens in a new window and not as a popup. The hyperlink in question has its target attribute set to _blank. Taking a clue from the answers that I got (Thanks guys !), I tried setting onclick = "window.location.reload()" and it works perfectly fine.
However I have a problem. In fact another question altogether. How to make sure that the reload of page A waits until the page opened in the new window (page B) loads ?
Something like this:
open page b
The simplest way would be to do
link
If I remember correctly that should open the window and then since the return has not been suppresed will reload load the page.
I am not exactly sure if this is what you want based on your wording, but if you want to reload the opening window from a link in the popup try
self.opener.location.href = self.opener.location.href;
Edit, based on your new comments just use the code above in the body onload of the new window
<body onload="self.opener.location.href = self.opener.location.href;">
You can use setTimeout() to delay the reload.
Try this:
<script type="text/javascript">
function openPage(elem) {
function reloadCurrentPage() {
location.reload();
}
var page = window.open(elem.href, '_blank');
page.onload = function() {
reloadCurrentPage();
}
if (/MSIE/.test(navigator.userAgent)) { // fix for IE
var timer = setInterval(function() {
if (page.document.readyState == 'complete') {
clearInterval(timer);
reloadCurrentPage();
}
}, 100);
}
}
</script>
<p>second.html</p>