- window.open with headers
- Answers
- window.open with headers
- Javascript Solutions
- Solution 1 — Javascript
- Solution 2 — Javascript
- Solution 3 — Javascript
- Solution 4 — Javascript
- Solution 5 — Javascript
- Solution 6 — Javascript
- Use POST instead
- Window.Open with Headers
- How to add request headers as array to window.open post url in javascript?
- $window.open with context / headers
- how to add authentication header to $window.open
- window.open with headers
- window.open with headers
window.open with headers
Can I control the HTTP headers sent by window.open (cross browser)?
If not, can I somehow window.open a page that then issues my request with custom headers inside its popped-up window?
I need some cunning hacks.
Answers
Can I control the HTTP headers sent by window.open (cross browser)?
If not, can I somehow window.open a page that then issues my request with custom headers inside its popped-up window?
- You can request a URL that triggers a server side program which makes the request with arbitrary headers and then returns the response
- You can run JavaScript (probably saying goodbye to Progressive Enhancement) that uses XHR to make the request with arbitrary headers (assuming the URL fits within the Same Origin Policy) and then process the result in JS.
It might help if you described the problem instead of asking if possible solutions would work.
You can’t directly control this, because it’s an option controlled by Internet Explorer users.
Opening pages using Window.open with a different window name will open in a new browser window like a popup, OR open in a new tab, if the user configured the browser to do so.
A more detailed explanation:
1. In modern browsers, window.open will open in a new tab rather than a popup.
2. You can force a browser to use a new window (‘popup’) by specifying options in the 3rd parameter
3. If the window.open call was not part of a user-initiated event, it’ll open in a new window.
4. A “user initiated event” does not have to the same function call – but it must originate in the function invoked by a user click
5. If a user initiated event delegates or defers a function call (in an event listener or delegate not bound to the click event, or by using setTimeout for example), it loses it’s status as “user initiated”
6. Some popup blockers will allow windows opened from user initiated events, but not those opened otherwise.
7. If any popup is blocked, those normally allowed by a blocker (via user initiated events) will sometimes also be blocked. Some examples…
Forcing a window to open in a new browser instance, instead of a new tab:
window.open('page.php', '', 'width=1000');
The following would qualify as a user-initiated event, even though it calls another function:
function o() < window.open('page.php'); >$('button').addEvent('click', o);
The following would not qualify as a user-initiated event, since the setTimeout defers it:
function g() < setTimeout(o, 1); >function o() < window.open('page.php'); >$('button').addEvent('click', g);
window.open with headers
Can I control the HTTP headers sent by window.open (cross browser)?
If not, can I somehow window.open a page that then issues my request with custom headers inside its popped-up window?
I need some cunning hacks.
Javascript Solutions
Solution 1 — Javascript
> Can I control the HTTP headers sent by window.open (cross browser)?
> If not, can I somehow window.open a page that then issues my request with custom headers inside its popped-up window?
- You can request a URL that triggers a server side program which makes the request with arbitrary headers and then returns the response
- You can run JavaScript (probably saying goodbye to Progressive Enhancement) that uses XHR to make the request with arbitrary headers (assuming the URL fits within the Same Origin Policy) and then process the result in JS.
> I need some cunning hacks.
It might help if you described the problem instead of asking if possible solutions would work.
Solution 2 — Javascript
If you are in control of server side, it might be possible to set header value in query string and send it like that? That way you could parse it from query string if it’s not found in the headers.
Just an idea. And you asked for a cunning hack 🙂
Solution 3 — Javascript
Sadly you can’t control headers when doing window.open()
Nice and easy, how I managed to open a file with custom headers:
const viewFile = async (url) => < // Change this to use your HTTP client fetch(url, /*YOUR CUSTOM HEADER*/> ) // FETCH BLOB FROM IT .then((response) => response.blob()) .then((blob) => < // RETRIEVE THE BLOB AND CREATE LOCAL URL var _url = window.URL.createObjectURL(blob); window.open(_url, "_blank").focus(); // window.open + focus >).catch((err) => < console.log(err); >); >;
Solution 4 — Javascript
As the best anwser have writed using XMLHttpResponse except window.open , and I make the abstracts-anwser as a instance.
The main Js file is download.js Download-JS
// var download_url = window.BASE_URL+ "/waf/p1/download_rules"; var download_url = window.BASE_URL+ "/waf/p1/download_logs_by_dt"; function download33() < var sender_data = "start_time":"2018-10-9", "end_time":"2018-10-17">; var x=new XMLHttpRequest(); x.open("POST", download_url, true); x.setRequestHeader("Content-type","application/json"); // x.setRequestHeader("Access-Control-Allow-Origin", "*"); x.setRequestHeader("Authorization", "JWT " + localStorage.token ); x.responseType = 'blob'; x.onload=function(e)"test211.zip", "application/zip" ); > x.send( JSON.stringify(sender_data) ); // post-data >
Solution 5 — Javascript
>You can’t directly add custom headers with window.open() in popup window but to work that we have two possible solutions
>1. Write Ajax method to call that particular URL with headers in a separate HTML file and use that HTML as url in window.open() here is abc.html
$.ajax(< url: "ORIGIONAL_URL", type: 'GET', dataType: 'json', headers: < Authorization : 'Bearer ' + data.id_token, AuthorizationCheck : 'AccessCode ' +data.checkSum , ContentType :'application/json' >, success: function (result) < console.log(result); >, error: function (error) < >>);
>here CORS policy can block the request if CORS is not enabled in requested URL.
>2. You can request a URL that triggers a server-side program which makes the request with custom headers and then returns the response redirecting to that particular url.
Suppose in Java Servlet(/requestURL) we’ll make this request
String[] responseHeader= new String[2]; responseHeader[0] = "Bearer " + id_token; responseHeader[1] = "AccessCode " + checkSum; String url = "ORIGIONAL_URL"; URL obj = new URL(url); HttpURLConnection urlConnection = (HttpURLConnection) obj.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setRequestProperty("Content-Type", "application/json"); urlConnection.setRequestProperty("Accept", "application/json"); urlConnection.setRequestProperty("Authorization", responseHeader[0]); urlConnection.setRequestProperty("AuthorizationCheck", responseHeader[1]); int responseCode = urlConnection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) < BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String inputLine; StringBuffer response1 = new StringBuffer(); while ((inputLine = in.readLine()) != null) < response1.append(inputLine); > in.close(); response.sendRedirect(response1.toString()); // print result System.out.println(response1.toString()); > else < System.out.println("GET request not worked"); >
call servlet in window.open(‘/requestURL’)
Solution 6 — Javascript
Use POST instead
Although it is easy to construct a GET query using window.open() , it’s a bad idea (see below). One workaround is to create a form that submits a POST request. Like so:
type="button" onclick="loadNnextPage()" value="Click me!">
Of course you will need something on the server side to handle this; as others have suggested you could create a «proxy» script that sends headers on your behalf and returns the results.
Problems with GET
- Query strings get stored in browser history,
- can be shoulder-surfed
- copy-pasted,
- and often you don’t want it to be easy to «refresh» the same transaction.
Window.Open with Headers
Can I control the HTTP headers sent by window.open (cross browser)?
If not, can I somehow window.open a page that then issues my request with custom headers inside its popped-up window?
- You can request a URL that triggers a server side program which makes the request with arbitrary headers and then returns the response
- You can run JavaScript (probably saying goodbye to Progressive Enhancement) that uses XHR to make the request with arbitrary headers (assuming the URL fits within the Same Origin Policy) and then process the result in JS.
It might help if you described the problem instead of asking if possible solutions would work.
How to add request headers as array to window.open post url in javascript?
You cannot use window.open to do POST request to the backend service, what you could do would be use fetch function
fetch(url, method: "POST",
body: JSON.stringify(),
headers:
.then(response => response.json())
.then(data => console.log(data));
You could also try using XMLHttpRequest
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() if (xhr.readyState === 4) console.log(xhr.response);
>
>
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.send(JSON.stringify());
$window.open with context / headers
Download the file first, then open it:
var url = this.apiBaseUrl + "/exportToExcel/" + id;
var headers = //Put headers here
>;
var config = <
responseType: 'blob',
headers: headers
>;
$http.get(url, config).then(function (response) var blob = response.data;
var u = URL.createObjectURL(blob);
window.open(u,"_blank");
>);
This will GET the file as a blob, convert it to a object URL, then open it in a new window.
how to add authentication header to $window.open
I think you can add this authentication parameters in URL and do a GET in your server side
//Add authentication headers as params
var params = access_token: 'An access_token',
other_header: 'other_header'
>;
//Add authentication headers in URL
var url = [url_generating_pdf, $.param(params)].join('?');
//Open window
window.open(url);
window.open with headers
Can I control the HTTP headers sent by window.open (cross browser)?
If not, can I somehow window.open a page that then issues my request with custom headers inside its popped-up window?
- You can request a URL that triggers a server side program which makes the request with arbitrary headers and then returns the response
- You can run JavaScript (probably saying goodbye to Progressive Enhancement) that uses XHR to make the request with arbitrary headers (assuming the URL fits within the Same Origin Policy) and then process the result in JS.
It might help if you described the problem instead of asking if possible solutions would work.
window.open with headers
Can I control the HTTP headers sent by window.open (cross browser)?
If not, can I somehow window.open a page that then issues my request with custom headers inside its popped-up window?
- You can request a URL that triggers a server side program which makes the request with arbitrary headers and then returns the response
- You can run JavaScript (probably saying goodbye to Progressive Enhancement) that uses XHR to make the request with arbitrary headers (assuming the URL fits within the Same Origin Policy) and then process the result in JS.
It might help if you described the problem instead of asking if possible solutions would work.
If you are in control of server side, it might be possible to set header value in query string and send it like that? That way you could parse it from query string if it’s not found in the headers.
Just an idea. And you asked for a cunning hack 🙂
Sadly you can’t control headers when doing window.open()
Nice and easy, how I managed to open a file with custom headers:
const viewFile = async (url) => < // Change this to use your HTTP client fetch(url,*YOUR CUSTOM HEADER*/> ) // FETCH BLOB FROM IT .then((response) => response.blob()) .then((blob) => < // RETRIEVE THE BLOB AND CREATE LOCAL URL var _url = window.URL.createObjectURL(blob); window.open(_url, "_blank").focus(); // window.open + focus >).catch((err) => < console.log(err); >); >;