I want to know a protocol of a site which is not my current page
E.g. I execute code and the current page which the code is executed on is http://www.example.org, and I want to get the protocol of which is https:
What I know is window.location.protocol should return the current page, which is http:, but is there something like 'google.com'.protocol to return https: ..
Thank you :)
My code:
var returnProtocolOf(site_url) = function {
return (String(site_url)).location.protocol // VIRTUAL COMMAND
};
You can do so with a elements:
function getProtocol(url){
var link = document.createElement('a');
link.href = url;
return link.protocol;
}
You can also just match it with an expression:
var protocol = url.match(/^([a-z]+?:)\/\//)[1];
Checks might be needed.
Related
My school blocked CTRL + U, but you can use 'view-source:' before a link to view the code. It takes awhile, so i've been trying to make a script to automatically direct to the source code. However, I keep getting errors because it is not a link
I have tried the following:
var code = fetch(`view-source:https://${location.hostname}${location.pathname}`);
location.href = (code);
and
var code = (`view-source:https://${location.hostname}${location.pathname}`);
location.href = (code);
In the first one, I see a bad request, and in the second, I a blank page with the words "view-source:" followed by the link
view-source: isn't a real protocol you can fetch().
However, just
var resp = await fetch('http://...');
var text = await resp.text();
document.body.textContent = text;
should replace the current document's body with the text contents of that URL...
If you try from frontend to fetch the source code you will run to CORS Problems. But you can use some proxyies like in the example beloow:
fetch('https://api.codetabs.com/v1/proxy?quest=https://stackoverflow.com/questions/75440023/script-to-get-source-code-of-website-js#75440023').then((response) => response.text()).then((text) => console.log(text));
How do I redirect conditionally with query /xxx?xxx in the url link?
For example, anyone who come to my site with the below two link should be redirected to different pages.
mysite.com/contest?a => mysite.com/contest-a
mysite.com/contest?b => mysite.com/contest-b
Can this be done using both js and meta refresh?
How do I do this using .htaccess?
If there is a querystring, replace the first instance of ? with -
if (window.location.search.length)
window.location.href = window.location.href.replace('?','-');
Use
location.href
to detect url, where you are now. And
window.location.replace('mysite.com/contest-a ');
to do redirect.
But probably it is better to do it on server side, since it will be faster.
you can use the below script to do the re-direction.
window.onload = function()
{
var location = window.location;
if(location.indexOf("contest?a") > -1)
{
window.location.href = "mysite.com/contest-a";
}
else
{
window.location.href = "mysite.com/contest-b";
}
}
It's not possible to change the url without refreshing the page (except for hashes), and thus you would be better off not using that url in the first place to avoid unnecessary requests and hassle for the user. You could take a look at mod_rewrite which does that (transform a "nice url" from the user into an "ugly url" that your server actually understands)
In your example, a possible rule might be
RewriteRule ^mysite.com/contest-{.+} /mysite.com/contest?$1
If you're ok doing this kind of operation on the client side, you could embed the following snippet on your landing page (the page where the arriving user will be redirected), just after the <head> tag:
<script type="text/javascript">
var mapReferrer = function() {
var gotoURL;
switch(document.referrer) {
case "https://www.google.com": gotoURL = "http://<yoursite>/arrivedFromSearchEngine"; break;
case "https://www.facebook.es": gotoURL = "https://<yoursite>/engageFBusers"; break;
case "http://<yoursite>/contest?b": gotoURL = "http://<yoursite>/contest-b"; break;
};
if (gotoURL) window.location = gotoURL;
};
window.onload = mapReferrer;
</script>
In making a function that validates a user URL and prepends http: at the front, I have to take cases of www, https and // into account as being valid urls. The way I have it written now (see below), I only prepend http: , so that cases of //stackoverflow.com don't turn into http: ////stackoverflow.com.
This means that a url like stackoverflow.com becomes http:stackoverflow.com.
In Firefox and Chrome, this works just fine, but these URLS will be clicked from a variety of browsers and devices. Is it something that'll work universally? It'll be easy to rewrite this check for a // case, but I'm interested in the answer.
Prepend method:
function prependHTTPtoWebURL() {
var url = (el('org_website').value);
var httpVar;
var testFor;
if (url) {// If there's a website URL value
testFor = url.toLowerCase();
if (testFor.indexOf("http") != 0){
httpVar = 'http:'; //add it
url = httpVar + url;
el('org_website').value = url;
}
}
}
Try playing with regex. Check this code for instance:
var someurl = "www.google.com";
var otherurl = "google.com";
var anotherurl = "//google.com";
function prependHTTPtoWebURL(url) {
var newurl = url.replace(/^(http)?(:)?(\/\/)?/i,'');
return 'http://' + newurl;
}
console.log(prependHTTPtoWebURL(someurl));
console.log(prependHTTPtoWebURL(otherurl));
console.log(prependHTTPtoWebURL(anotherurl));
The ouput in console.log will be:
http://www.google.com
http://google.com
http://google.com
Since you are specifying a subdomain (www) on the first one, that is respected. It avoids ending with four diagonals, like http:////. If your url was something like :google.com, it would also fix it correctly.
You can see it live here: http://jsfiddle.net/zRBUj/
Edit: Adding the /i Kate mentioned.
Change http: to http://
See these links for more info:
Anatomy of a URL
How the web works
first timer here so be nice :3.
I am attempting to write a jQuery function that rewrites Amazon URL's to include affiliate tags, similar to what StackExchange does but with a twist.
The main differences is that I am attempting to the user to their closest Amazon Store - e.g. amazon.de - for german visitors. Due to Amazon's ASIN's differing in some countries I first want to check the new link, if it 404's I obviously don't want to direct my visitor there [1]
Here is my code that selects links to amazon.com, grabs the ASIN number and writes a shortlink to the product including the affiliate tag.
var tld_table = {'GB' : ".co.uk",'DE' : ".de",'CN' : ".cn",'AU' : ".ca",'IT' : ".it",'FR' : ".fr",'CA' : ".ca",'JP' : ".jp",};
var country = $.cookie("CountryCode");
//$.cookie by http://plugins.jquery.com/files/jquery.cookie.js.txt
var tld = tld_table[country] || '.com';
var regex = RegExp("http://www.amazon.com/([\\w-]+/)?(dp|gp/product)/(\\w+/)?(\\w{10})");
$('a[href*="amazon.com"]').each(function(){
var url = $(this).attr('href');
m = url.match(regex);
if (m) { //if ASIN found
var ASIN = m[4];
var shorturl = "http://www.amazon"+tld+"/dp/" + ASIN + "?tag="+ affTag[tld];
//http test for 404
//if 404 do not rewrite
//else $(this).attr('href',shorturl);
}
});
This works fine and will re-write the URL's but when I introduce ajax into the equation the script fails to rewrite any URL's.
EDIT
$('a[href*="amazon.com"]').each(function(){
var url = $(this).attr('href');
m = url.match(regex);
if (m) { //if ASIN found http://www.amazon.com/dp/B003DZ1Y8Q/?tag=derp
var ASIN = m[4];
var ajaxCall = $.get('ASIN.php?ASIN='+ASIN+'&tld='+tld+'&tag='+affTags[tld], function(data) {
var newlink = data;
console.log('New Link: '+newlink)
$(this).attr('href',newlink); //does not rewrite
})
ajaxCall.success(function() {
if(newlink != '404'){
$(this).attr('href',newlink);//does not rewrite
}
})
}
});
Above is the code I am attempting to use currently, ASIN.php builds & requests the new link, opens it using php's cURL and returns either a new link or '404'.
I think $(this) is failing to reference the link correctly, but I have no idea why.
The error says it all: is not allowed by Access-Control-Allow-Origin
It basically means that your javascript is not allowed to retrieve any URL outside of your domain. You can fix this by rewriting your ajax request to a local PHP script that checks the url.
It has something to do with http://en.wikipedia.org/wiki/Same_origin_policy
you can also use apache mod_proxy
ProxyPass /mirror/foo/ http://foo.com/
Then you can call the url /mirror/foo/ on your domain and it will pass the request to the forwarding remote url.
This is a common way of overcoming cross-domain browser restrictions.
http://httpd.apache.org/docs/1.3/mod/mod_proxy.html#proxypass
I'm currently using the following function to 'convert' a relative URL to an absolute one:
function qualifyURL(url) {
var a = document.createElement('a');
a.href = url;
return a.href;
}
This works quite well in most browsers but IE6 insists on returning the relative URL still! It does the same if I use getAttribute('href').
The only way I've been able to get a qualified URL out of IE6 is to create an img element and query it's 'src' attribute - the problem with this is that it generates a server request; something I want to avoid.
So my question is: Is there any way to get a fully qualified URL in IE6 from a relative one (without a server request)?
Before you recommend a quick regex/string fix I assure you it's not that simple. Base elements + double period relative urls + a tonne of other potential variables really make it hell!
There must be a way to do it without having to create a mammoth of a regex'y solution??
How strange! IE does, however, understand it when you use innerHTML instead of DOM methods.
function escapeHTML(s) {
return s.split('&').join('&').split('<').join('<').split('"').join('"');
}
function qualifyURL(url) {
var el= document.createElement('div');
el.innerHTML= 'x';
return el.firstChild.href;
}
A bit ugly, but more concise than Doing It Yourself.
As long as the browser implements the <base> tag correctly, which browsers tend to:
function resolve(url, base_url) {
var doc = document
, old_base = doc.getElementsByTagName('base')[0]
, old_href = old_base && old_base.href
, doc_head = doc.head || doc.getElementsByTagName('head')[0]
, our_base = old_base || doc_head.appendChild(doc.createElement('base'))
, resolver = doc.createElement('a')
, resolved_url
;
our_base.href = base_url || '';
resolver.href = url;
resolved_url = resolver.href; // browser magic at work here
if (old_base) old_base.href = old_href;
else doc_head.removeChild(our_base);
return resolved_url;
}
Here's a jsfiddle where you can experiment with it: http://jsfiddle.net/ecmanaut/RHdnZ/
You can make it work on IE6 just cloning the element:
function qualifyURL(url) {
var a = document.createElement('a');
a.href = url;
return a.cloneNode(false).href;
}
(Tested using IETester on IE6 and IE5.5 modes)
I found on this blog another method that really looks like #bobince solution.
function canonicalize(url) {
var div = document.createElement('div');
div.innerHTML = "<a></a>";
div.firstChild.href = url; // Ensures that the href is properly escaped
div.innerHTML = div.innerHTML; // Run the current innerHTML back through the parser
return div.firstChild.href;
}
I found it a little more elegant, not a big deal.
URI.js seems to solve the issue:
URI("../foobar.html").absoluteTo("http://example.org/hello/world.html").toString()
See also http://medialize.github.io/URI.js/docs.html#absoluteto
Not testeed with IE6, but maybe helpful for others searching to the general issue.
I actually wanted an approach to this that didn't require modifying the original document (not even temporarily) but still used the browser's builtin url parsing and such. Also, I wanted to be able to provide my own base (like ecmanaught's answer). It's rather straightforward, but uses createHTMLDocument (could be replaced with createDocument to be a bit more compatible possibly):
function absolutize(base, url) {
d = document.implementation.createHTMLDocument();
b = d.createElement('base');
d.head.appendChild(b);
a = d.createElement('a');
d.body.appendChild(a);
b.href = base;
a.href = url;
return a.href;
}
http://jsfiddle.net/5u6j403k/
This solution works in all browsers.
/**
* Given a filename for a static resource, returns the resource's absolute
* URL. Supports file paths with or without origin/protocol.
*/
function toAbsoluteURL (url) {
// Handle absolute URLs (with protocol-relative prefix)
// Example: //domain.com/file.png
if (url.search(/^\/\//) != -1) {
return window.location.protocol + url
}
// Handle absolute URLs (with explicit origin)
// Example: http://domain.com/file.png
if (url.search(/:\/\//) != -1) {
return url
}
// Handle absolute URLs (without explicit origin)
// Example: /file.png
if (url.search(/^\//) != -1) {
return window.location.origin + url
}
// Handle relative URLs
// Example: file.png
var base = window.location.href.match(/(.*\/)/)[0]
return base + url
However, it doesn't support relative URLs with ".." in them, like "../file.png".
This is the function I use to resolve basic relative URLs:
function resolveRelative(path, base) {
// Absolute URL
if (path.match(/^[a-z]*:\/\//)) {
return path;
}
// Protocol relative URL
if (path.indexOf("//") === 0) {
return base.replace(/\/\/.*/, path)
}
// Upper directory
if (path.indexOf("../") === 0) {
return resolveRelative(path.slice(3), base.replace(/\/[^\/]*$/, ''));
}
// Relative to the root
if (path.indexOf('/') === 0) {
var match = base.match(/(\w*:\/\/)?[^\/]*\//) || [base];
return match[0] + path.slice(1);
}
//relative to the current directory
return base.replace(/\/[^\/]*$/, "") + '/' + path.replace(/^\.\//, '');
}
Test it on jsfiddle: https://jsfiddle.net/n11rg255/
It works both in the browser and in node.js or other environments.
I found this blog post that suggests using an image element instead of an anchor:
http://james.padolsey.com/javascript/getting-a-fully-qualified-url/
That works to reliably expand a URL, even in IE6. But the problem is that the browsers that I have tested will immediately download the resource upon setting the image src attribute - even if you set the src to null on the next line.
I am going to give bobince's solution a go instead.
If url does not begin with '/'
Take the current page's url, chop off everything past the last '/'; then append the relative url.
Else if url begins with '/'
Take the current page's url and chop off everything to the right of the single '/'; then append the url.
Else if url starts with # or ?
Take the current page's url and simply append url
Hope it works for you
If it runs in the browser, this sort of works for me..
function resolveURL(url, base){
if(/^https?:/.test(url))return url; // url is absolute
// let's try a simple hack..
var basea=document.createElement('a'), urla=document.createElement('a');
basea.href=base, urla.href=url;
urla.protocol=basea.protocol;// "inherit" the base's protocol and hostname
if(!/^\/\//.test(url))urla.hostname=basea.hostname; //..hostname only if url is not protocol-relative though
if( /^\//.test(url) )return urla.href; // url starts with /, we're done
var urlparts=url.split(/\//); // create arrays for the url and base directory paths
var baseparts=basea.pathname.split(/\//);
if( ! /\/$/.test(base) )baseparts.pop(); // if base has a file name after last /, pop it off
while( urlparts[0]=='..' ){baseparts.pop();urlparts.shift();} // remove .. parts from url and corresponding directory levels from base
urla.pathname=baseparts.join('/')+'/'+urlparts.join('/');
return urla.href;
}