I used a variation of the above but instead of printing html I built a form and submitted it to the 3rd party url:

    var mapForm = document.createElement("form");
    mapForm.target = "Map";
    mapForm.method = "POST"; // or "post" if appropriate
    mapForm.action = "http://www.url.com/map.php";

    var mapInput = document.createElement("input");
    mapInput.type = "text";
    mapInput.name = "addrs";
    mapInput.value = data;
    mapForm.appendChild(mapInput);

    document.body.appendChild(mapForm);

    map = window.open("", "Map", "status=0,title=0,height=600,width=800,scrollbars=1");

if (map) {
    mapForm.submit();
} else {
    alert('You must allow popups for this map to work.');
}
Answer from php-b-grader on Stack Overflow
Top answer
1 of 1
1

Try with HttpSession to save the state of the user specific data that can be accessed by any page within the same domain.

Steps to follow:

  • Simply make a GWT RPC call to pass the JSON string to the server in post request.
  • At server side of RPC call save the JSON string in HTTP Session to access it later
  • Now open a new page (having same domain) that will access the JSON string from the HTTP Session

Complete Sample code including GWT PRC classes as well

@RemoteServiceRelativePath("greet")
public interface GreetingService extends RemoteService {
    public void setJSON(String json)throws IllegalArgumentException;
}

public interface GreetingServiceAsync {  
    void setJSON(String json, AsyncCallback<Void> callback);
}

public class GreetingServiceImpl extends RemoteServiceServlet implements GreetingService {
    @Override
    public void setJSON(String json) throws IllegalArgumentException {
        // set the JSON string in HTTP Session
        getThreadLocalRequest().getSession().setAttribute("json", json);
    }
}

web.xml:

<servlet>
    <servlet-name>greetServlet</servlet-name>
    <servlet-class>com.x.y.z.server.GreetingServiceImpl</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>greetServlet</servlet-name>
    <url-pattern>/modulename/greet</url-pattern>
</servlet-mapping>

Entry Point class:

GreetingServiceAsync greetingService = GWT.create(GreetingService.class);
public class GWTProject implements EntryPoint {
    public void openNewWindow(final String json) {
        greetingService.setJSON(json, new AsyncCallback<Void>() {

            @Override
            public void onFailure(Throwable caught) {

            }

            @Override
            public void onSuccess(Void result) {
                // open any page within the same domain
                Window.open("/page.jsp", "", "");
            }
        });
 }
Discussions

html - Is it possible to use Javascript to open a new window, POST paramaters to the new window, while passing the request as application/json? - Stack Overflow
Now the JSON is going over the wire in its native format, solving the encoding problem. But now the call to window.document.open() resets the URL of the new window to the URL of the parent. If the new window is refreshed, it redirects to the parent window. And even if that wasn't the case, there's no POST data ... More on stackoverflow.com
🌐 stackoverflow.com
Window.open and pass parameters by post method
With window.open method I open new site with parameters, which I have to pass by post method.I've found solution, but unfortunately it doesn't work. This is my code: More on stackoverflow.com
🌐 stackoverflow.com
September 3, 2013
I there a simple way of sending JSON data using $window.open() and angularjs?
2 what is the most elegant way of opening a pop up window with angular and receiving data from it on the parent More on stackoverflow.com
🌐 stackoverflow.com
May 13, 2017
Window.open() vs $.get()
Hi, I am running a few tests for my Quote Machine Challenge App. Besides Twitter, I’d linke to share the quotes as well to Hubzilla. Running window.open(hubzillaQueryLink) will open a new window and post fine according to the queryString. Now I thought I might want to get the JSON that’s ... More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
0
0
August 2, 2017
Top answer
1 of 10
147

Instead of writing a form into the new window (which is tricky to get correct, with encoding of values in the HTML code), just open an empty window and post a form to it.

Example:

<form id="TheForm" method="post" action="test.asp" target="TheWindow">
<input type="hidden" name="something" value="something" />
<input type="hidden" name="more" value="something" />
<input type="hidden" name="other" value="something" />
</form>

<script type="text/javascript">
window.open('', 'TheWindow');
document.getElementById('TheForm').submit();
</script>

Edit:

To set the values in the form dynamically, you can do like this:

function openWindowWithPost(something, additional, misc) {
  var f = document.getElementById('TheForm');
  f.something.value = something;
  f.more.value = additional;
  f.other.value = misc;
  window.open('', 'TheWindow');
  f.submit();
}

To post the form you call the function with the values, like openWindowWithPost('a','b','c');.

Note: I varied the parameter names in relation to the form names to show that they don't have to be the same. Usually you would keep them similar to each other to make it simpler to track the values.

2 of 10
78

Since you wanted the whole form inside the javascript, instead of writing it in tags, you can do this:

let windowName = 'w_' + Date.now() + Math.floor(Math.random() * 100000).toString();
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", "openData.do");

form.setAttribute("target", windowName);

var hiddenField = document.createElement("input"); 
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", "message");
hiddenField.setAttribute("value", "val");
form.appendChild(hiddenField);
document.body.appendChild(form);

window.open('', windowName);

form.submit();
🌐
To The New
tothenew.com › home › how to send a post request in window.open() function of javascript.
How to send a POST request in window.open() function of JavaScript. | TO THE NEW Blog
December 19, 2016 - I googled a lot and found few JavaScript code snippets that provides some workaround for doing this stuff. Finally, I found some cool way for sending POST request in window.open().
🌐
Oodlestechnologies
oodlestechnologies.com › blogs › open-popup-window-with-http-post-data-javascript
Open popup window with http POST data Javascript
February 14, 2020 - function openPopupPage(relativeUrl, emailId, age) { var param = { 'emailId' : emailId, 'age': age }; OpenWindowWithPost(relativeUrl, "width=1000, height=600, left=100, top=100, resizable=yes, scrollbars=yes", "NewFile", param); } function OpenWindowWithPost(url, windowoption, name, params) { var form = document.createElement("form"); form.setAttribute("method", "post"); form.setAttribute("action", url); form.setAttribute("target", name); for (var i in params) { if (params.hasOwnProperty(i)) { var input = document.createElement('input'); input.type = 'hidden'; input.name = i; input.value = params[i]; form.appendChild(input); } } document.body.appendChild(form); //note I am using a post.htm page since I did not want to make double request to the page //it might have some Page_Load call which might screw things up.
Find elsewhere
🌐
Taswar Bhatti
taswar.zeytinsoft.com › home › javascript http post data to new window or pop up
Javascript http post data to new window or pop up - Taswar Bhatti
August 22, 2014 - Thank you very much (Y) For a new windows, we can pass ‘_blank’ in the name param. And it worked for me without window.open and that was great. ... Works perfectly!!!! ... Came across this post – thank you for this nice script.
🌐
freeCodeCamp
forum.freecodecamp.org › t › window-open-vs-get › 169384
Window.open() vs $.get()
August 2, 2017 - Hi, I am running a few tests for my Quote Machine Challenge App. Besides Twitter, I’d linke to share the quotes as well to Hubzilla. Running window.open(hubzillaQueryLink) will open a new window and post fine according to the queryString. Now I thought I might want to get the JSON that’s ...
🌐
Stack Overflow
stackoverflow.com › questions › 42480284 › how-to-open-a-new-window-and-send-out-a-post-request-with-json-data-in-the-new-w
How to open a new window and send out a POST request with JSON data in the new window using JavaScript? - Stack Overflow
Create a new window object using window.open(). Set a JavaScript function to execute on window.onload. In the JavaScript function defined in step 2, send a XMLHttpRequest for POST data using JSON.
🌐
JSFiddle
jsfiddle.net › RR7RK
send data via post into a popup (different domains) - JSFiddle - Code Playground
JSFiddle - Test your JavaScript, CSS, HTML or CoffeeScript online with JSFiddle.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › API › Fetch_API › Using_Fetch
Using the Fetch API - Web APIs | MDN
const response = await fetch("https://example.org/post", { method: "POST", body: JSON.stringify({ username: "example" }), // … }); You can supply the body as an instance of any of the following types: ... Other objects are converted to strings using their toString() method.
🌐
Google Groups
groups.google.com › g › google-web-toolkit › c › 9BQFfiO6fzg
How to send Post-Data to Window.open?
> If not, what other possibilities do I have? You can send a POST in response to which the server generates a temporary file and sends back the URL to that file, and then use Window.open with that URL to open the generated file in a new window.
Top answer
1 of 1
12

If you just want a link that opens a POST-requested page in a new window here are some ideas. However, be aware a POST request can't be bookmarked.

  • You can make a button that opens a POST-requested page in a new window.

    <form method="post" action="http://example.com/example.php"
      target="_blank">
    <input type="hidden" name="name1" value="value1">
    <input type="hidden" name="name2" value="value2">
    <input type="submit" value="Open results in a new window"> 
    </form>
    
  • If you want it to look like a link, you can make a link with an onClick attribute that submits the form.

    <form name="myform" method="post" action="http://example.com/example.php"
      target="_blank">
    <input type="hidden" name="name1" value="value1">
    <input type="hidden" name="name2" value="value2">
    </form>
    
    <a href="http://example.com/example.php"
      onClick="document.forms['myform'].submit(); return false;">Open results
      in a new window</a>
    

    The onClick part submits the form, which opens the POST-requested page in a new window. The return false prevents the browser from also going to the href address in the current window at the same time. If Javascript is disabled or the link is bookmarked, the href address is used as a fallback, but the resulting page won't receive any POST values. This might be confusing or unfriendly for your users if they bookmark the link.

If you want the link to be bookmarkable, investigate if your page can accept GET parameters. If so, then you can make a bookmarkable link.

 <a href="http://example.com/example.php?name1=value1&name2=value2"
   target="_blank">Open results in a new window</a>
🌐
Coderanch
coderanch.com › t › 493054 › languages › pass-JSON-Object-window-window
How to pass JSON Object to another window using window.open (HTML Pages with CSS and JavaScript forum at Coderanch)
April 26, 2010 - programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums · this forum made possible by our volunteer staff, including ... ... Hi I am getting JSON reponse from server into my JSP Page . Now my requirement is i ned to send this JSON response to another window using window.open.
Top answer
1 of 4
1

Hello Philipp

Welcome to the Microsoft Community.

This is not a bug but a result of how the Edge JSON Viewer behaves when opening a URL programmatically via window.open. Here's an explanation of what's happening and how you can address the issue:

Explanation:

  1. Manual URL Entry:
    • When you manually input the JSON URL in Edge's address bar, Edge knows it's serving JSON content and uses its built-in JSON Viewer to pretty-print it.
  2. window.open() Behavior:
    • When you use window.open() to programmatically open the URL, Edge does not automatically invoke its JSON Viewer. Instead, it treats the opened page as plain text or raw JSON, and the pretty-print functionality is not applied.
  3. Reason:
    • Edge's JSON Viewer may only be triggered when the request is a direct manual navigation or when the JSON content is properly formatted and served with the correct Content-Type (application/json) header, but window.open doesn't trigger the JSON Viewer in the same way.

Solutions:

  1. Manually Open the URL
  • The simplest workaround is to let the user click the JSON URL (e.g., Open JSON), which will behave like manual navigation and trigger the JSON Viewer.
  1. Open the JSON in a New Tab with Pretty Formatting
  • You can use a JavaScript library (e.g., JSON.stringify) to pretty-print the JSON content before displaying it in a new tab or window. Example:
      fetch("https://api.open-meteo.com/v1/forecast?latitude=52.52&longitude=13.41&hourly=temperature_2m")
          .then(response => response.json())
          .then(data => {
              const prettyJSON = JSON.stringify(data, null, 2); // Pretty printconst newWindow = window.open();
              newWindow.document.write(`
    ${prettyJSON}
    `); newWindow.document.close(); });
    This fetches the JSON data, formats it nicely, and displays it in a new window or tab using
     tags.
  1. Use an External JSON Viewer Tool
  • If you frequently need to pretty-print JSON, you can use tools like:
    • jsonviewer.stack.hu
    • jsonformatter.org
    • These tools can take raw JSON data and pretty-print it in a visually appealing manner.
    • Disclaimer: This is a non-Microsoft website. The page appears to be providing accurate and safe information. Watch out for ads on the site that may advertise products frequently classified as PUP (Potentially Unwanted Products). Thoroughly research any product advertised on the site before you decide to download and install it.

Summary:

  • The behavior you're seeing is by design and not a bug. To ensure JSON is always pretty-printed when using window.open, either fetch the data and format it programmatically (Solution 2) or let the user manually click a link (Solution 1).

Best Regards,

William.Y | Microsoft Community Support Specialist

2 of 4
0

Thanks, I implemented the change and and the users are now clicking on a simple link in the javascript/angular UI, if they decide to view the plain JSON data from the WebService and this is working fine. The JSONViewer is opening when clicking a simple link (was not opening when using window.open(...)).
Strange behaviour, thanks for the workaround, this did solve my problem.
Greetings
Philipp