Relative URL to a different port number in a hyperlink? - html

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>
...

Related

Firefox redirect section bug

I'm trying to redirect to my price section of my webiste by the following link: https://www.paydomestic.com.br/#pricing
Google chrome works correctly, already in firefox does not work.
but this only occurs via link, if you put the url "https://www.paydomestic.com.br/#pricing" and press enter in the browser works, but not via link!
why is that?
Solved
<script>
/*location.hash returns the anchor part of an URL as a string,
with hash (#) symbol included. */
//wait for page elements to load
//execute function only if the anchor exists in the URL address
window.onload = function() {if(location.hash){
//remove # from the string
var elId = location.hash.replace('#','');
//locate the anchored element on the page by its ID property
var scrollToEl = document.getElementById(elId);
//scroll to the anchored element
scrollToEl.scrollIntoView(true);
}
}
</script>

HTML Redirecting with text before the domain

I'm working on a Website and I was wondering how can I check if it has some text before the domain, for instance:
shop.website.com
If it starts with shop. before the domain, then I want to redirect them to another page.
How do I do that?
You can use regular expression for checking whether there is text before the domain.
example:
<script>
function myFunction()
{
var str = "shop.world.com";
var patt = /(\w*)\.\w*\.\w*/g;
var result = patt.exec(str);
if( result!=null)
{
if(result[1]=="shop")
{
//redirect the page
window.location.href="anotherPage.html";
}
}
}
</script>
If the result is not null then there is text before the domain.As we have remembered the text before the domain by using parenthesis in our regular expression we can easily compare it with string "shop" and if it matches then redirect the page.
for more information on regular expression you can visit this page
http://www.w3schools.com/jsref/jsref_obj_regexp.asp
window.location.href will provide you the URL of the current page.
Use window.location.replace(..) to redirect the user.
Although in your case you may configure sub-domains on your web server. Refer the following link for more on sub-domains:
http://support.hostgator.com/articles/cpanel/what-is-a-subdomain-name-how-do-i-create-and-delete-one

open mail sending prompt in new tab using mailto: [duplicate]

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.

Opening javascript links in new tab

(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/

Chrome extension used to refresh pages

I was trying to develop a Chrome extension that can display me the last 3 news from a soccer news site (obviously the page is not open in any tab), by refreshing every 5 minutes. My ideea was to load the page inside an iframe and, once the page is loaded, access the page DOM and extract only the text nodes with the news. I've tried in many ways using ready and load functions, I tried to follow this solutions here but i always get warnings. My question is: is there a way I can do that without having troubles with cross-domain security? Are there any simple examples i can use?
Here's how you could do it using JQuery (please keep in mind I dont know JQuery, just saw this approach somewhere and thought it might work for you).
I put this in a popup and it worked....
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script>
function renderNews(newsList){
$('#news').html('');
$(newsList).each(function(i,item){
var link = document.createElement('a');
$(link).attr('href',item.link);
$(link).html(item.description);
$(link).click(function(){
chrome.tabs.create({url:$(this).attr('href')});
});
var linksDate = document.createElement('span');
//$(linksDate).text(item.date);
$(linksDate).text(item.day + '-' + item.month + ' ' + item.hour + ':' + item.minute+' - ');
var listItem = document.createElement('li');
$(listItem).append(linksDate).append(link);
$("#news").append(listItem);
});
}
function getNews() {
$.get("http://www.milannews.it/?action=search&section=32", null, function(data, textStatus)
{
if(data) {
var news=$(data).find(".list").find('li').slice(0,3) ;
$("#status").text('');
var newsList=[];
$(news).each(function(i, item){
var newsItem={};
newsItem.description=$(item).find('a').html();
newsItem.link='http://www.milannews.it/'+$(item).find('a').attr('href');
newsItem.date=$(item).find('span').first().text();
newsItem.day=newsItem.date.split(' ')[0].split('.')[0];
newsItem.month=newsItem.date.split(' ')[0].split('.')[1];
newsItem.hour=newsItem.date.split(' ')[1].split(':')[0];
newsItem.minute=newsItem.date.split(' ')[1].split(':')[1];
newsList[i]=newsItem;
});
renderNews(newsList);
localStorage.setItem('oldNews',JSON.stringify(newsList));
}
});
}
function onPageLoad(){
if (localStorage["oldNews"]!=null) renderNews(JSON.parse(localStorage["oldNews"]));
getNews();
}
</script>
</head>
<body onload="onPageLoad();" style="width: 700px">
<ul id="news"></ul>
<div id="status">Checking for new news...</div>
</body>
</html>
And dont forget to put the urls your getting with the xhr stuff in the permissions part of your manifest....
http://code.google.com/chrome/extensions/xhr.html
Use xhr to load the page and use jQuery or a regex to parse the raw HTML for the data you are looking for.
Keep in mind that the destination site may not want to you access their site in such an automated fashion. Be respectful of their site and resources.