Javascript Get Website URL - javascript

How do I get Javascript to tell me the website url.
For example if I have a page www.example.com/page.html
I want Javascript to tell me the site url is www.example.com and not www.example.com/page.html (which document.location tells me)
Is there a way to do this? If so, how?
Thanks in advance for your help :)

There are several ways you can do this, but one way might be best for certain situations (e.g. within an iFrame).
Protocol + Domain + Page
document.URL
> "http://example.com/page1.html"
document.location.href
> "http://example.com/page1.html"
Protocol + Domain
document.location.origin
> "http://example.com"
Domain
document.location.host
> "example.com"
Page
document.location.pathname
> "/page1.html"

There are many ways to get this.
Open Chrome browser and press F12, you'll get console.
Type following commands there for the same question URL. You will get your answer
window.location.hostname // Output : stackoverflow.com
window.location.origin // Output : http://stackoverflow.com
document.location.host // Output : stackoverflow.com

Use
window.location.hostname
You can test it by just typing it in the chrome dev tools console
Reference
MDN: https://developer.mozilla.org/en-US/docs/Web/API/Location

use
document.location.origin+document.location.pathname;
where document.location.origin will redirect you to "http://www"
and document.location.pathname will redirect you to "/stackoverflow/"(Name of your project).
In this way you can give reference to page or post you want in your js file.Suppose if i want reference to my home page i would have use
var address=document.location.origin+document.location.pathname;
window.location.replace(address+"/home");
So using above example i can easily redirect to my homepage

Try this
document.location.host

Use alert(window.location.origin) for getting the url.

Try
document.location.origin
That will give you the protocol and host.

you can also use location.href = '/' + 'path_name/sub_path_name'
'/' = takes you to the home page then
'path_name/sub_path_name' = to pass the new path to the domain page

Related

Jquery.get not working with ssl

I recently added an SSL certificate to my website and since then some of the jquery functions are no longer working. Specifically jquery.get
Example:
function getBfeForm() {
jQuery.get('/wp-admin/admin.php/?page=booking.multiuser.5.3/wpdev-booking.phpwpdev-booking-resources&tab=availability&wpdev_edit_avalaibility=<?php echo key($_REQUEST['avail']); ?>/', function(data) {
jQuery('[name="avail['+<?php echo key($_REQUEST['avail']); ?>+']"]').removeClass('spinner').val('Edit Availability');
if (data) {
jQuery('#availHolder .holder').html(jQuery(data).find('.inside'));
jQuery('#availHolder .holder').prepend('<div id="popHeader"><a title="Close" class="fancybox-item fancybox-close" href="javascript:;">Close</a></div>');
jQuery('#availHolder').hide();
jQuery('#availHolder').appendTo(jQuery('[data-resource="<?php echo key($_REQUEST['avail']); ?>"]').find('tr.clean td'));
jQuery('#availHolder').slideDown(500);
}
});
}
This function works fine with http but when SSL is activated and https used the function no longer calls the file. I have seen other comments on here saying the lack of trailing slashes is the issue, but I believe I have added trailing slashes correctly now and it still doesn't work.
Any help would be greatly appreciated.
UPDATE: I added alert("Data: " + data + "\nStatus: " + status); to the function to see what data was actually being served. It appears the wordpress log in page is being called rather than the file specified in the function. I have tested this on a duplicate site without SSL and it calls the correct file. Does this mean the SSL is not allowing a link to wp-admin files?
If you are using windows and have a local certificate installed in IIS then try access the site with fully qualified name of the computer
[computer_name].[domain_name]
For example: [ox-pchris11].[companyname.com] where ox-pchris11 is the computer name and companyname.com is the domain name.
if you access the site as localhost it will show a error page which will ask permission to continue.
I found the problem and posting the answer here for anyone else who is implementing an SSL certificate. The issue was the custom login page we have. We are using the wp_signon function and we had $user_verify = wp_signon( $login_data, false );. This should be $user_verify = wp_signon( $login_data, true ); - setting the value to 'true' creates a secure cookie. If the cookie is not secure, each time a user tries to access wp-admin files they are logged out and required to log in again.
For details check the wordpress codex for wp_signon.

is it possible to redirecturl without changing url

I'm creating a chrome extension that if you domain.com, it will redirect you to domain.com.ipaddress.com
Here's the main code:
chrome.webRequest.onBeforeRequest.addListener(function (details) {
var url = details.url.split("/")[2];
var url = "http://" + url + ".ipaddress.com";
return { redirectUrl: url };
}, {
urls: ['*://*/*']
}, ['blocking']);
My problem is how do i display the contents of domain.ipaddress.com without the changing the url (domain.com). Because when i visit google.com the url text changes to google.com.ipaddress.com
I know i'm bad at explaining. To understand more, im gonna express what i want using an image.
Thankfully, that's not possible.
You can't influence the address bar, it will show the actual source of the page / final redirected address.
As noted in comments, to permit otherwise would be a severe security problem.

Getting the current domain name in Chrome when the page fails to load

If you try to load with Chrome: http://sdqdsqdqsdsqdsqd.com/
You'll obtain:
ERR_NAME_NOT_RESOLVED
I would like, with a bookmarklet, to be able to get the current domain name and redirect it to a whois page in order to check if the domain is available.
I tried in the console:
window.location.href
but it outputs:
"data:text/html,chromewebdata"
Is there any way to retrieve the failed URL?
The solutions given by others didn't work (maybe because I was getting a different error or have a newer version: Chrome 55):
document.querySelector('strong[jscontent="hostName"]').textContent
but the same can be achieved via:
document.querySelector('#reload-button').url
A potentially more future-proof version (from Thomas's comment)
loadTimeData.data_.summary.failedUrl
So a cross-version solution incorporating all workarounds:
var url = (l‌​ocation.href === 'data‌​:text/html,chromeweb‌​data'
&& loadTimeData.data_.summary.failedUrl
|| document.querySelector('#reload-button').url
) || location.href;
var hostname = (l‌​ocation.href === 'data‌​:text/html,chromeweb‌​data'
&& loadTimeData.data_.summary.hostName
|| document.querySelector('strong[jscontent="hostName"]').textContent
) || location.hostname;
On the Chrome error page, location.href doesn't point to the domain you tried to visit, since it's an internally-hosted page.
However, the domain name you tried to visit is available if you expand the "Show Details" link.
You can run this code in console (or a bookmarklet) to parse out the domain name:
document.querySelector('strong[jscontent="hostName"]').textContent
A modified version of nderscore's since you'll need to have an if statement for the return of the correct one.
function getUrl () {
if(window.location.hostname == "") {
return document.querySelector('strong[jscontent="hostName"]').textContent
} else{
return window.location.href;
}
}
While looking in source code of html page using Developer Tools (right-click on a web page, and select Inspect Element), I've found that full original failed URL is in a variable called
loadTimeData.data_.summary.failedUrl
In my case I have to update some 'incorrect part' of auto generated URL to 'correct part'. So I've created bookmarlet like this:
javascript: location.assign(loadTimeData.data_.summary.failedUrl.replace('IncorrectPart','CorrectPart'));

do something if window.history location is from www.example.com

how can we determine if window.history is from a certain URL like www.example.com , and then do something for example :
if ( //window.history includes example.com string ) {
$('.myclassname').hide()
}
it actually needs to know the link location of history ... is there any way to find it out ?
You can only get the referer(the page user came from) via document.referer. You can't access history from js.

Secure/Non-secure browsing issue

I am developing a Facebook app that incorporates our Brightcove (video host) players and their API. Facebook gives users the option to browse securely and this poses a little bit of a problem. As is stands, I can get the app to work properly on one of the protocols (http or https), but not both.
https://www.facebook.com/atlantafalcons?sk=app_292392080815275 (change to http:// to see it not working)
If I set the BrightcoveExperiences.js file source to https://sadmin.brightcove.com/js/BrightcoveExperiences.js then it throws errors when someone is not browsing securely. If I set it to http://admin.brightcove.com/js/BrightcoveExperiences.js then it throws errors when someone is browsing securely.
The documentation for embedding securely is here: http://support.brightcove.com/en/docs/publishing-brightcove-player-https-page
Is there a way to detect if the user is browsing securely to be able to choose which JS file to load or is there a way to force users to browse securely? Or is there another workaround for a problem like this?
Thanks in advance!
EDIT:
Was able to come up with a solution (thanks to scibuff for recommending to check google analytics):
<script type="text/javascript">
var bJsHost = (("https:" == document.location.protocol ) ? "https://sadmin." : "http://admin.");
document.write(unescape("%3Cscript src='" + bJsHost + "brightcove.com/js/BrightcoveExperiences.js' type='text/javascript'%3E%3C/script%3E"));
</script>
Use a scheme-relative URI:
//admin.brightcove.com/js/BrightcoveExperiences.js
And don't use different hostnames for the SSL and non-SSL instances.
(Or have sadmin respond with a 301 redirect to admin for non-SSL requests)
I would go with Quentin's suggestion. Although, using your suggestion, you can use:
// window, top, self, document, others?
window.location.protocol
In other words:
if (window.location.protocol == 'http:') {
document.body.innerHTML = 'The page is using the http (non-secure) protocol.';
} else {
document.body.innerHTML = 'The page is using the https (secure) protocol.';
}
http://jsfiddle.net/3NREg/
Other window/document objects might work as well, depending on what you need:
// window, top, self, document, others?
if (self.location.protocol == 'http:') {
document.body.innerHTML = 'The page is using the http (non-secure) protocol.';
} else {
document.body.innerHTML = 'The page is using the https (secure) protocol.';
}
http://jsfiddle.net/3NREg/1/

Categories

Resources