Search code examples
javascriptpostdynamicuserscripts

Javascript - accessing elements from an unopened page


My question is somewhat difficult to explain. What I am trying to do is, I have a button on a certain page. When I press that button, I must be able to access elements of a form that is located on another page (without having the other page open).

Pressing that button will edit some of the elements in the form from that "unopened" page, and then post it, all this without opening any extra popup/tab/window. After the form has been posted, the button will disappear.

The form in question contains unique parameters that can't be retrieved without accessing its particular page, so I cannot emulate the form in standalone.

Some of my guesses are to use a dynamic iframe set to "display: none", or Ajax, but otherwise I'm not exactly sure if it is possible and how to do it.

Would anybody have some ideas? (sorry if the question isn't very clear, I tried my best to describe the problem)


Solution

  • I did it this way, using jQuery:

    1. Acquire HTML code from the form page using $.get()
    2. Extract the form node from the HTML string
    3. Create an hidden iframe
    4. Parse the form's HTML inside the new iframe
    5. Modify the form's values;
    6. "URLEncode" the form's data using jQuery's .serialize();
    7. Post the serialized data to the target using $.post(), with a callback function receiving the response
    8. If response indicates success, hide the button and remove the hidden iframe

    I decided to extract the form out of the HTML string returned by $.get(), since parsing it won't require to load the whole form page before using the actual form as an object. Using an hidden iframe for parsing is probably not the most "professional" way, but it works.