What is a good way to obtain the end URL if given a URL that is being forwarded to another URL?
For example, if I had the shortened URL: http://bit.ly/900913, what is a good way to determine that this ultimately forwards to http://www.google.com?
I'm using javascript. I'm unsure if this can be done somehow using jQuery (doubtful since the end URL probably isn't returning jsonp content) or if there is some kind of web service that I can use.
Thanks!
For bit.ly specifically, you can use the bit.ly API to make a JSONP call using JavaScript to expand the bit.ly URL(s) in question.
Specifically, you'd use the v3/expand call.
Pseudo-code:
var bitlyurl = "http://bit.ly/900913";
$.getJSON("http://api.bitly.com/v3/expand?shortUrl=" + encodeURIComponent(bitlyurl)+"&apikey=...&callback=?", function( bitlydata ){
var endurl = bitlydata.data.expand[0] //looks like this is where the end URL would point
});
Alternately, you could follow the URL on your own server, and use AJAX to check it's values.
So, you'd pass it a URL ($.get("/follow?url="+bitlyurl,function(data){var endurl = data.Location;});, and make a HEAD call to the URL to see where the Location points.
Here's the basics of how you'd do it in PHP:
<?php
$headers = get_headers($_GET["url"],1);
echo json_encode($headers);
?>
Just for fun, I implemented a live end-point on App Engine to check where a URL points. Feel free to use it! The base URL is followtheredirect.appspot.com, and it requires a url parameter and a callback parameter, and returns a location key on the resulting object, when successful.
Sample code:
$.getJSON("http://followtheredirect.appspot.com/?url="+encodeURIComponent('http://bitly.com/hhN7Ol')+"&callback=?",function(data){
var location = data.location;
});
Let me know if you find any bugs :) it might be a bit messy...
Bitly provides a preview service. If you visit http://bit.ly/900913- (notice the hyphen at the end), you'll get a response with the full URL.
Related
I am wondering how to deal with a simple redirect. I have a domain, for example: stackguy.com. And I want to redirect users to specific URLs from this url.
Let's say, stackguy.com/redirect=youtube.com/watch/xxx
And this URL (youtube.com...) needs to be elastic. What the user enters, it should redirect to the website the user wants.
I have totally no idea, to be honest. I've tried to do it by using database and by separating all urls but it's a lot of work and can't be automated easily.
It can also be done like stackguy.com/red=<id of YT video>
Doesn't matter to me.
The other solution talks about using javascript which runs on the client side. And you probably want this on the server side.
You still need to use a parameter
stackguy.com?redirect=https://www.youtube.com/watch/xxx
But you can use php to do the redirect.
$par = filter_var ($_GET ['redirect'] ?? '', FILTER_SANITIZE_STRING);
if ($par)
{header('Location: ' . $par, true, 302); }
The first line gets the parameter after sanitizing it. It returns blank if its null (or missing)
The second line checks if there is a string
The third line does a redirect using a 302. This is a temporary redirect, I wouldn't advise using a 301 (permanent).
Note that this will only work if the PHP file has done NO HTML output.
I think you should use query parameters for this and handle the redirect in your javascript. Instead of:
stackguy.com/redirect=youtube.com/watch/xxx
use
stackguy.com?redirect=https://www.youtube.com/watch/xxx
Then in your js you can check if the redirect paramter is set and redirect the user to the link in the query parameter.
Here is an example:
function redirectUrl() {
// Get the value of the "redirect" query parameter
const redirect = new URLSearchParams(window.location.search).get("redirect");
// If the "redirect" parameter is not null, redirect the user to the specified URL
if (redirect) {
window.location = redirect;
}
}
To use the function you will need to call it in your code for example:
window.addEventListener("load", redirectUrl);
let's say one of my urlpatterns looks like this.
url('^objects/update/(?P<pk>\d+)$', views.UpdateView.as_view(), name = 'update-object'),
I need to redirect user to the update page depending on the selected object (the list of objects is populated using Ajax). So I'd like to pass that named url pattern to the JavaScript, in order to build the actual url on the client side.
Example of what I want to achieve:
pass the name 'update-objects' to the function
get the actual url pattern, replace (?P<pk>..) with {pk}
pass the result to the javascript, resulting in : objects/update/{pk}
any tips?
thanks
to make it more clear: at the moment of rendering, I can't do url reverse because the PK is not known yet. I need to make kind of javascript-urlpattern which will later be converted to the real url (i.e. my JS code will replace {pk} part with the actual pk value)
The actual URL reversing must happen on the server side. There are several ways to do this, and the most elegant of these probably depends on how exactly your script and markup are set up for this. One thing I've done recently is to attach the URL to a logical element using HTML5 data attributes, which are easy to retrieve using jQuery. If you're not using jQuery, I'll leave it up to you to translate to pure JS. You haven't provided any code or specifics for your client-side, so I'm kind of shooting in the dark here, but maybe this will give you the idea:
Django HTML template:
<ul class="object-list">
{% for object in objectList %}
<li data-update-url="{% url update-objects object.pk %}">object.name</li>
{% endfor %}
</ul>
JS:
$('.object-list').on('click', 'li' function () {
var updateUrl = $(this).data('update-url')
...
});
It sounds like you need to make an additional ajax call once the object has actually been selected. Don't try and second guess your url.conf by trying to work out the url on the client side - you'd just be making trouble for yourself later. Wait till you can get a pk, then use django's reverse function to give you your url (doing anything else violates DRY).
How about creating a simple view that returns the url -
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseBadRequest
def get_url(request):
if request.is_ajax() and request.method == 'POST':
obj_id = request.POST['obj_id']
url = reverse('object-update', kwargs{'pk': obj_id})
return HttpResponse(obj_id)
return HttpResponseBadRequest()
Then write a javascript function that gets the url using an ajax call to your new view and then redirects. You'd call this function as soon as the object's been selected. I would suggest using JQuery to do this, pure javascript will require you to write more code, and probably write browser specific code (depending on your target). Also it supports dealing with django's csrf protection (you'll need to implement this for ajax calls if you haven't already).
var redirect = function(obj) {
$.ajax({
url: '/your-get-url-view/',
method: 'post',
data: {'obj_id': obj},
success: function(url){
window.location = url;
}
});
}
I'm afraid I don't know how you're getting from the selected object to the pk (For simplicity I've assumed it's available to the redirect function) - you may have to do some processing in the view to get there.
I haven't tested the above code, but it should give you an idea of what I'm suggesting.
Try this one:
Reverse method for generating Django urls
https://github.com/mlouro/django-js-utils
One more
https://github.com/Dimitri-Gnidash/django-js-utils
If you have a URL that only has one PK field in it, you could resolve it with any number (e.g. 0), then substitute the number as required.
In my scenario my URL had a pk then an upload_id, so I had to replace on the right most instance of a 0, with <upload_id>, which the JS would replace this string occurance as required:
detele_url_upload_id_0 = reverse(f'{APP_NAME}:api_upload_delete', args=[pk, 0])
prefix, suffix = detele_url_upload_id_0.rsplit('0', 1)
context['generic_delete_url'] = prefix + '<upload_id>' + suffix
Then in the JS:
const deleteUrl = genericDeleteUrl.replace('<upload_id>', uploadId)
I am calling another application context from window.showModalDialog but confused with following work. Same code to pass parameter within showModalDialg.
var myArguments = new Object();
myArguments.param1 = "Hello World :)";
window.showModalDialog("java2sTarget.html", myArguments, '');
and i can read these myArguments(parameters) in generated HTML using following code:
<script>
document.write(window.dialogArguments.param1);//Hello World :)
</script>
I can't use query string & i am sending myArguments(parameter) because i want to hide parameter from Application user.
Now i am calling servlet from showModalDialog(..)
onclick="window.showModelDialog('http://localhost:7778/app/servlet/test',myArguments,'');"
onclick="window.showModelDialog('http://localhost:7778/app/servlet/test',myArguments,'');"
But as per my knowledge
Servlet --> Servlet container --> HTML+JS+CSS
so JS will be available at last phase, but i want to use in first phase(Servlet).
Now, i need to make some Decision in servelt code based on myArguments(parameter).
is there any way to read these myArguments(parameters) in servlet code?
Pass it as a request parameter in the query string.
var queryString = "param1=" + encodeURIComponent("Hello World :)");
onclick="window.showModelDialog('http://localhost:7778/app/servlet/test?' + queryString, myArguments, '');"
No, there's no other alternative. The request URL is not visible in the modal dialog anyway.
As main objective is to hide query string from User to avoid misuse of those parameters.
I tried following work around.
Developers send hidden parameters to get relative information form source(e.g.:DataBase). And we also know that we can send hidden information in Window.showModalDialog using dialogArguments
Work Around:
(i) I got relative information from server one-step before calling Window.showModalDialog using jQuery.getJSON()
(ii) i used google-gson API at servlet side to convert JavaBeans into Json strings.Solution 1 Solution 2
(iii) Convert JSON into javascript object using jQuery.parseJSON
var args = jQuery.parseJSON(json);
window.showModalDialog("pages/"+args.pageName, args, '');
i used args.pageName to make things dynamic
Please suggest improvements in this work-around. Thanks
I'm really confused how many times should I encode a URL when it is set as a value in a querystring 'coz we know browser has their own encoding process. Here's the scenario:
I want to redirect to another location which I want to pass the previous URL:
Note: the current URL is http://localhost:8081/CostMonitoring/MainMenu.aspx?Option=AllCE
Method A (without encodeURIComponent()):
window.location = 'CostEstimateApproval.aspx?CEMID=40' +
'&ToStatus=1CE'+
'&PrevURL=' + window.location;
I get this in the address bar
http://localhost:8081/CostMonitoring/CostEstimateApproval.aspx?CEMID=40&ToStatus=1CE&PrevURL=http://localhost:8081/CostMonitoring/MainMenu.aspx?Option=AllCE
without encodeURIComponent(), everything works fine and the value of Request.Querystring("PrevURL") in the receiving page is
http://localhost:8081/CostMonitoring/MainMenu.aspx?Option=AllCE
which is correct.
Method B (with encodeURIComponent()):
window.location = 'CostEstimateApproval.aspx?CEMID=40' +
'&ToStatus=1CE'+
'&PrevURL=' + encodeURIComponent(window.location);
with this method I get this in the address bar:
http://localhost:8081/CostMonitoring/CostEstimateApproval.aspx?CEMID=40&ToStatus=1CE&PrevURL=http%3A%2F%2Flocalhost%3A8081%2FCostMonitoring%2FMainMenu.aspx%3FOption%3DAllCE
and the value of Request.Querystring("PrevURL") in the receiving page is
http://localhost:8081/CostMonitoring/MainMenu.aspx?Option=AllCE
which is also decoded correctly.
My questions:
Should I encode the URL-as-value? Will it be redundant if I encode it then the browser encode it again?
or should I let the browser encode it for me? If I let the browser, will the receiving page be confused from URL-as-a-value's value to the real URL value? Please consider this example:
http://www.domain.com/newpage.aspx?SameName=DifferentValue&PrevURL=http://www.domain.com/oldpage.aspx?SameName=DifferentValue&PrevURL=http://www.domain.com/anypage.aspx
as you can see, both URL (the real URL and the URL-as-a-value) when not encoded has the same data name which is SameName. How does the receiving side handle this? or the HTTP server?
Thanks in advance!
You should use encodeURIComponent (once), since you're encoding a url parameter.
As you noted at the end of your question, failing to encode the url with encodeURIComponent would be problematic if your url included an &, for example.
Note that your Method A only worked because your example prevUrl is somewhat simply formed, e.g. it doesn't include a second url parameter.
I want to redirect after a successful ajax request (which I know how to do) but I want to pass along the returned data which will be used to load an iframe on the page I just redirected to.
What's the best way to pass such data along and use it to open and populate an iframe in the page I just redirected to?
EDIT:
I am passing a GET variable but am having to use the following to access it for use in my iframe src attribute:
function $_GET(q,s) {
s = (s) ? s : window.location.search;
var re = new RegExp('&'+q+'=([^&]*)','i');
return (s=s.replace(/^\?/,'&').match(re)) ? s=s[1] : s='';
}
var d = $_GET('thedata');
I assume there isn't really a more straightforward way to access the GET vars?
If it's not too much data, you could pass it as a get parameter in the redirect:
document.location = "/otherpage?somevar=" + urlescape(var)
Remember that urls are limited to 1024 chars, and that special chars must be escaped.
If it is beyond that limit your best move is to use server side sessions. You will use a database on the server to store the necessary information and pass a unique identifier in the url, or as a cookie on the users computer. When the new page loads, it can then pull the information out of the database using the identifier. Sessions are supported in virtually every web framework out of the box.
Another alternative may be to place the data as a hidden attribute in a form which uses the post method (to get around the 1024 char limit), and simulating a submission of the form in javascript to accomplish the redirect, including the data.