Reputation: 416
I am trying to find a way to prefill an external HTML form/Input with data possibly using Javascript? I do not own the website that the form is on, so that makes things difficult. Is there any way to do this?
Upvotes: 2
Views: 2755
Reputation: 75706
The only way I’ve been able to manipulate sites I don’t control is with a bookmarklet. An extension can be used too but a bookmarklet is easier and has no restrictions.
…now if I could just do this on mobile somehow.
Upvotes: 0
Reputation: 5063
Now, this is almost surely not going to help you. But, for the sake of completeness: there is one way to communicate with an iframe, even if it is cross-origing: the postMessage
API.
The way it works is simple. On your website you do:
let win = document.getElementById("iframe").contentWindow;
win.postMessage(JSON.stringify({ key: value }));
And the iframe has to be listening for the postMessage
, like this:
document.addEventListener("message", function(e){
console.log("Domain:", e.domain, "sent", e.data);
});
Of course you'd have to contact the iframe
developer and arrange for them to listen to your post, and furthermore to pre-fill the form with whatever you send as data
. In many scenarios, this is unrealistic. But it is possible.
Accessing any element of an iframe that does not reside in the same domain, is the definition of cross-side(-frame) scripting.
However, if you were to get the page on the same domain it would be easy to prefill the form.
A parent frame can have access to an <iframe>
elements using the DOM API. Let's set up our constants:
const iframe = document.getElementById('iframeId');
const innerDoc = iframe.contentDocument || iframe.contentWindow.document;
You have to have knowledge of the structure of the page that your are embedding. Assuming you do, with innerDoc
you can access the fields that need to be pre-filled.
Let's take an example. Say that the form in the <iframe>
looks like this
<form>
<label>Some field
<input name="an-input" type="text"/>
</label>
</form>
To fill the input
element we simply do
const input = innerDoc.querySelector("[name='an-input']");
input.value = "Filler text";
Upvotes: 2