enforce http with JavaScript - javascript

I have a srcURL variable which gets a path of the form /myFolder/myFile.jpg
Now this gets assigned to the img element..which obviously would call it with the complete path https://mySite.com/myFolder/myFile.jpg
Now I somehow want the https to be replaced/enforced with http using Javascript..
I am not sure if I can do this with the "replace()" method since I only get the path "/myFolder/myFile.jpg" in the srcURL variable and not with https..
How can I do that?

You are using a relative path. You need to use an explicit path when setting the src of the URL.
srcURL = '/myFolder/myFile.jpg';
srcURL = 'http://' + window.location.host + srcURL;
// srcURL == 'http://<yourdomainname>/myFolder/myFile.jpg'
Note: you'll probably get a warning message saying some parts of your page may be unsecure.

If you want to enforce plain HTTP, you should write a rewrite rule on the server to forward any HTTPS request for an image to the HTTP equivalent. On the client side, simply doing this would be sufficient (but you really need the back end piece too):
url.replace("https", "http");

Related

JQuery use value for location.href

How to I use a JQuery value for a url to use with location.href?
The url will be different every time the below url is an example.
The URL is stored in the database as
audit.php?audit=13957911461655047299&page=summary
Ajax is then used to retrieve the URL and save in a var called last_viewed so I would like to use the equivalent of
location.href = last_viewed
I have tried
location.href = '"'+last_viewed+'"'
but the URL becomes
http://www.x-rayqa.co.uk/"audit.php?audit=13957911461655047299&page=summary"
which obviously won't work because of the extra "s
if I try just
location.href = last_viewed
nothing happens, the script is broken.
If you don't add anything to the URL in your example, the browser assumes it's a relative URL and prefixes it with the current location origin (http://www.x-rayqa.co.uk on your site). If that stored link is on the same server, you'll need to ensure the path is correct after the server name.
If it's not local (i.e., an external link) then you'll have to add the server and protocol prefix yourself to make the link work. Take a look at the window.location documentation as well, which might help clear some things up.
https://developer.mozilla.org/en-US/docs/Web/API/Window.location
You can assign directly to window.location.href or use window.location.assign().

How do I set window.location to a specific path (without a host)?

I am using the window location method to redirect a webpage to another after a set amount of time.
The url needs to change from www.myurl.com/home to www.myurl.com/other. The problem is that I do not know what the final URLs will be so I cannot use absolute links, they have to be a path only. This is what I have so far:
window.location.pathname = "mobility.html"
You can just prepend a / to your URL to make them relative to the domain root (without having to hardcode the domain name). Like this:
window.location = "/mobility.html"
window.location.assign("/path") also works.

How should I create relative paths in javascript using MVC3?

I am having some difficulty aligning my paths without a hardcode in javascript. I am running an asp.net MVC3 web application.
If my path is of the form
var url = 'http://serverNameHardcode/websiteNameHardcode/service/service?param1=' + param;
Then things work fine when I do
$.get(url,
{},
function (data) {alert('callback success');},'json');
I would like to create a relative path. I tried
var url = 'service/service?param1=' + param;
And this works when I run locally and also in Firefox, but not in IE7. When I publish to the server without the hardcode the callback never fires. I know MVC-3 adds some complexity to routing, but I do not know if it applies to this situation; so, I marked this question as such.
How should I setup my path so I don't need hardcodes?
Just write out the app path as a global js variable from your master view, then compose links as
APPPATH + "path/whatever"
Just had to solve this for one of my jQuery plugins, where it is preferable not to modify anything global (i.e. outside the scope of the plugin use) so I had to disregard the marked answer.
I also found that because I host DEV locally in IIS I could not use a root-relative path (as localhost is not the root).
The solution I came up with extended what I had already started with: a data-controller attribute specifying which controller to use in the element I am applying my plugin to. I find it preferable to data-drive the controller names so the components can be more easily reused.
Previous:
<div data-controller="Section">
Solution:
<div data-controller="#Url.Content("~/Section")">
This injects the server root (e.g. /Test.WindowsAzure.Apr2014/ before the controller name so I wind up with /Test.WindowsAzure.Apr2014/Section which is perfect for then appending actions and other parameters as you have. It also avoids having an absolute path in the output (which takes up extra bytes for no good reason).
In your case use something like:
// Assuming $element points to the element your plugin/code is attached to...
var baseUrl = $element.data('controller');
var url = baseUrl + '/service?param1=' + param;
Update:
Another approach we now use, when we do not mind injecting a global value, is Razor-inject a single global JavaScript variable onto window in the layout file with:
<script>
window.SiteRoot = "#Url.Content("~/")";
</script>
and use it with
var url = window.SiteRoot + '/service?param1=' + param;
One option:
var editLink = '#Url.Action("_EditActivity", "Home")';
$('#activities').load(editLink + "?activityID=" + id);
another example:
var actionURL = '#Url.Action("_DeleteActivity", "Home")';
$('#activities').load(actionURL + "?goalID=" + gID + "&activityID=" + aID);
If you don't need to add to the string:
$('#activities').load('#Url.Action("_Activities", "Home", new { goalID = Model.goalID},null)');
I really need the path to get this to work, maybe its IE7. Who knows. But this worked for me.
Grab the URL and store it somewhere. I chose to implement the data attribute from HTML5.
<div id="websitePath" data-websitePath='#Request.Url.GetLeftPart(System.UriPartial.Authority)#Request.ApplicationPath'></div>
Then when you need to perform some AJAX or otherwise use a URL in javascript you simply refer to the stored value. Also, there are differences in the versions of IIS (not cool if your devbox is IIS5 and your server is IIS7). #Request.ApplicationPath may or may not come back with a '/' appended to the end. So, as a workaround I also trim the last character if it is /. Then include / as part of the url.
var urlprefix = $('#websitePath').data('websitepath');
urlprefix = urlprefix.replace(/\/$/, "");
var url = urlprefix + '/service/service?param1=' + param;
While the accepted answer is correct I would like to add a suggestion (i.e. how I do it).
I am using MVC, and any ajax request goes to a controller. My controllers have services so if a service call is required the controller will take of that.
So what's my point? So if ajax always communicates with a controller, then i would like to let the MVC routing resolve the path for me. So what I write in Javascript for url is something like this:
url: 'controller/action'
This way there is no need for the root path etc...
Also, you can put this in a separate Javascript file and it will also work whereas #Url.Content will need to be called on the view.

Can I get the referrer?

I have a website on which I dynamically create Javascript code using ASP.NET handler in which I should add the referrer to a database.
I want to get referrer of referrer like so:
website1
website2 (where I create pixel to another site)
website3 (where pixel is located)
I don't have code access to website1, on website2 I can only assign JavaScript.
If I get referrer in current application state I get website2.
Is there a way to get website1 as referrer?
You can pass this value along: document.referrer.
That expression would need to be evaluated on website 2, not on website 3.
So:
// website2.html
<img src="website3.com/pxl.gif" id="pxl" />
<script>
document.getElementById('pxl').src += '?ref=' + encodeURIComponent(document.referrer);
</script>
The request to website3 will then include the referrer.
It is impossible to get the referrer of website2 on website3 directly. However, since you can use javascript on website2, you could get the referrer (document.referrer) and add it to the url of the pixel you get. For example:
var referer = document.referrer;
var pixelUrl = 'http://website3/pixel?referrer=' + escape(referrer);
// create pixel...
Hope that helps
Seems that document.referrer doesn't work in many instances.
Use the complete window.frames.top.document.referrer instead.

Get the current url but without the http:// part bookmarklet!

Guys I have a question, hoping you can help me out with this one. I have a bookmarklet;
javascript:q=(document.location.href);void(open('http://other.example.com/search.php?search='+location.href,'_self ','resizable,location,menubar,toolbar,scrollbars,status'));
which takes URL of the current webpage and search for it in another website. When I use this bookmarklet it takes the whole URL including http:// and searches for it. But now I would like to change this bookmarklet so it will take only the www.example.com or just example.com (without http://) and search for this url. Is it possible to do this and can you please help me with this one?
Thank you!
JavaScript can access the current URL in parts. For this URL:
http://css-tricks.com/example/index.html
window.location.protocol = "http"
window.location.host = "css-tricks.com"
window.location.pathname = "/example/index.html"
please check: http://css-tricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/
This should do it
location.href.replace(/https?:\/\//i, "")
Use document.location.host instead of document.location.href. That contains only the host name and not the full URL.
Use the URL api
A modern way to get a part of the URL can be to make a URL object from the url that you are given.
const { hostname } = new URL('https://www.some-site.com/test'); // www.some-site.com
You can of course just pass window location or any other url as an argument to the URL constructor.
Like this
const { hostname } = new URL(document.location.href);
Do you have control over website.com other.example.com? This should probably be done on the server side.
In which case:
preg_replace("/^https?:\/\/(.+)$/i","\\1", $url);
should work. Or, you could use str_replace(...), but be aware that that might strip 'http://' from somewhere inside the URL:
str_replace(array('http://','https://'), '', $url);
EDIT: or, if you just want the host name, you could try parse_url(...)?
Using javascript replace via regex matching:
javascript:q=(document.location.href.replace(/(https?|file):\/\//,''));void(open('http://website.com/search.php?search='+q,'_self ','resizable,location,menubar,toolbar,scrollbars,status'));
Replace (https?|file) with your choice, e.g. ftp, gopher, telnet etc.

Categories

Resources