Finding the destination URL after a redirect using JavaScript

<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>

<script>
function updateRedirectURL(){
    var clientID = "hgffgh";
    var clientSecret = "fgfhgfh";
    var callbackUri = "https://login.live.com/oauth20_desktop.srf";
    
    var tokenUri = "https://www.box.com/api/oauth2/token";
    var authUri = "https://www.box.com/api/oauth2/authorize?"+
            "client_id="+clientID+
            "&response_type=code"+
            "&redirect_uri="+callbackUri

    //var web = window.open(authUri);
    //console.log(web.location.href); 
    
    var win = window.open(authUri, "windowname1", 'width=800, height=600'); 

    //alert(win)
}
</script>

After clicking on allow in the newly opened window, how can I retrieve the URL of the final redirection?

Answer №1

IMPORTANT: You have the ability to define variables in a redirect URL.


Prior to transitioning to the next page, specify "redir" as the URL for redirection (location.href) in your link, but make sure it is encoded as shown below:

"https://www.box.com/api/oauth2/authorize?redir=" + encodeURIComponent(location.href)

To obtain the redirect page, retrieve the variable "redir" from the current URL. Refer to this post. Subsequently, once you have obtained "redir", decode it:

var redirectPage = decodeURIComponent(url);

Answer №2

To achieve this using NodeJS, you can implement the following code:

var url = 'http://www.google.com';
request({ url: url, followRedirect: false }, function (err, res, body) {
  console.log(res.headers.location);
});

For more information, refer to this stackoverflow answer.

Alternatively, there is another solution provided in a discussion on Google Groups which involves correcting code errors from an answer available on GitHub. This solution also utilizes NodeJs JavaScript. Here's the corresponding piece of code:

var sys = require('system');
var pageUrl = ( sys.args[1] ) ? sys.args[1] : phantom.exit(0);

function forceExit(){
    phantom.exit(0);
}

var renderPage = function (url) {
    var page = require('webpage').create();
    
    page.onNavigationRequested = function(url, type, willNavigate, main) {
        var tmpUrl = ( url.substr(url.length - 1) != '/' ) ? url+'/' : url;
        var tmpPageUrl = ( pageUrl.substr( pageUrl.length - 1) != '/' ) ? pageUrl+'/' : pageUrl;
        console.log(tmpUrl,tmpPageUrl);
        if (main && tmpUrl!=tmpPageUrl ) {
            pageUrl = url;
            sys.stdout.write(url+'\n');
            setTimeout(forceExit,100 );
        }
    };

    page.open(url, function(status) {
        if ( status !== 'success' ) {
            phantom.exit( 1 );
        } else {
            phantom.exit( 0 );
        }
    },100);

    setTimeout(forceExit,2000 );
};

renderPage( pageUrl );

Answer №3

It is not within the realm of possibility. The capabilities of JavaScript are restricted to extracting information solely from its own webpage.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

UI-Router - templateUrl: "Ensure the content is securely delivered via HTTPS"

I am currently using HTTPS for my website. I have a requirement to send a request for templateUrl, not to a static file, but to the router: /:lang/content/library/book/:bookId Below is the setup for my state: .state('book', { url: '/ ...

Changing the href attribute of a link element when it is clicked

Currently, I am in the process of developing a dynamic hyperlink that enables the downloading of an image fetched from the server. Below is the code snippet I have been working with: In HTML: <a class="btn" id="controlDownloadJPEG" download>Save & ...

What is the method for incorporating a 3rd party npm module without utilizing npm install?

I'm in a situation where I need to utilize an outdated 3rd party npm module that cannot be directly used with npm i and reqiure. In order to customize it for my specific needs, I have to make some modifications to the source code of this npm module. ...

Is it important to maintain the scroll to top button at a consistent height?

I am facing an issue with my button. I want the button to remain at a consistent height even when the window size is adjusted vertically. How can I ensure that the button does not move or get pushed down as the height changes? http://jsfiddle.net/ccq9cs9L ...

Calculating date discrepancies with JavaScript

Two fields are present, one for the start date and one for the end date. I would like to display the date difference in another text box when the user selects dates from a date picker. Although I have made some progress on this, I believe that there are st ...

What could be the reason for my inability to transmit Express response object through SocketIO?

I'm attempting to send the response of an express request by transmitting it to a ws client and awaiting its feedback. This requires sending the res object to the client as I couldn't find an alternative method. This is what I have implemented: ...

`meteor.js and npm both rely on the fs module for file

I'm feeling a bit lost, as I need to use the fs package with Meteor.js framework. Starting from meteor version 0.6 onwards, I know that I should use Npm.require in the following way: var fs = Npm.require('fs'); However, when I try this, a ...

Utilizing the index of a generic type within TypeScript

I am attempting to design generic message types that become increasingly specific, with the most precise type being inferred during the function call or class creation. Consider the following code snippet: type MessageHeaderType = 'REQUEST'|&apo ...

Once the form is submitted, Vue automatically resets all the data

export default { data() { return { usrName: null, pass1: null, pass2: null, regState: {stateCode:-1}, } }, methods: { register: function () { this.axios.post("/login/", { baseURL: 'http://127 ...

Running a function exclusively within a single div using Angular 2

I am currently using *ngFor to group items, and it's functioning correctly. However, I am having trouble displaying the "listofGroup" in the view even though it works in the console. Specifically, I need to run a function within a specific div in Angu ...

Using the v-for directive before applying the Vue directive

I need help with displaying images in a carousel from data fetched via Firebase. I have created a directive, but the problem lies with the v-for loop. The directive is executed before the v-for loop, resulting in no items in the carousel. Directive: di ...

Uploading an image using ajax with multer

When using Multer to upload an image file to my Node server, I keep getting 'undefined' when trying to use ajax to send the image. Ajax : image = $("#input-file-img").val() const data = new FormData(); data.appe ...

Is there a way to continue a failed fetch request?

I am curious about the possibility of resuming an incomplete fetch request if it fails due to a non-code-related issue, like a lost network connection. In one of my current projects, we send a large download via AJAX to the client after they log in. This ...

React Native issue: why are my variables resetting mysteriously?

Hey there, I'm currently encountering a peculiar situation involving the usage of var and React.useState() variables. I am utilizing the library https://github.com/tongyy/react-native-draggable#readme to define 2 variables - var color1 = ''; ...

Is there a way for me to access the current templating in AngularJS?

I am looking to retrieve the HTML page as a string after AngularJS has finished rendering the template. My goal is to send this content to the server. .controller('MyCtrl', ['$scope', '$location', function ( $scope, $location ...

Develop a fresh AngularJS directive that utilizes the HTML5 audio element

Recently delved into Angular and managed to create audio buttons using an Angular directive: app.directive('soundButton', [function () { return { restrict: 'E', link: function (scope, element, attrs) { v ...

Achieving data synchronization and sequencing with AngularJS promises at a 1:1 ratio

Concern I am facing challenges with AngularJS promise synchronization and sequencing as my app expands across multiple controllers and services. In this scenario, I have an articles controller named ArticleController along with a related service named Art ...

Tips for patiently awaiting the completion of an API's creation and local audio file writing process prior to uploading it to an S3 bucket

I am currently utilizing an API to generate a TextToSpeech audio file on the local filesystem before uploading it to an S3 bucket. The package I am using for this process is called elevenlabs-api. The issue I am facing is that the code fails because it ta ...

Switching HTML text by clicking or tapping on it

I'm currently working on a website that will showcase lengthy paragraphs containing complicated internal references to other parts of the text. For instance, an excerpt from the original content may read: "...as discussed in paragraph (a) of section ...

A useful method for adding an element to a variable to display in a React component

In the scenario where you have a react component similar to the following (https://jsfiddle.net/69z2wepo/28684/): var Hello = React.createClass({ render: function() { let { cond, name } = this.props; let content, content2; if (cond){ c ...