tim
tim

Reputation: 3903

Bookmarklet target page DOM traversal. How?

How do I make a bookmarklet that places something into a field and submits the form?

I think along these lines:

1)var p = document.open(http://site.com/form.htm)

2) var h = p.innerHTML

3) var f = h.getElementById('formfield')

now how do I get the URL of the current page to become the value for 'formfield'?

Upvotes: 0

Views: 213

Answers (3)

Victor Dramba
Victor Dramba

Reputation: 121

If I understand correctly, you want to submit the current URL and maybe some other data to your server using a bookmarklet.

I would do it this way:

  1. Append your form to the current DOM using JavaScript. The form should be hardcoded in the bookmarklet.
  2. Populate the form, you are on the guest page now, same domain.
  3. Submit the form, maybe using a target="_blank" for the result.

You can't use Ajax instead of a form to submit your data because of crossdomain restrictions.

Upvotes: 0

DG.
DG.

Reputation: 3517

var p = document.open(http://site.com/form.htm)

This won't work. You may be thinking of window.open. If you use window.open, it will only be useful for your purposes if the bookmarklet is run from the same domain. If run from any other domain, it will open the window, but you won't be able to do anything else with the document in that newly opened window.

var h = p.innerHTML

This does nothing helpful in your case. It just returns a string of text.

var f = h.getElementById('formfield')

This is not correct because it uses "h", which isn't correct. What you probably want is this...

var w = window.open('http://site.com/form.htm');
// need code that will check if window is done loading before you use next line!
w.document.getElementById('formfield').value = window.location;

If you use the bookmarklet on the page with the form, you only need this:

document.getElementById('formfield').value = window.location;

If you want to open the window to another domain, enter a form value, and submit the form - This can not be done with a bookmarklet. A bookmarklet faces the same restrictions as any other javascript in a page. This is for security to prevent any web page on the internet from trying to take control of your browser and do things on other sites as you. Your only reasonable option in this case would be to create/use a browser addon/extension.

Upvotes: 1

Lucas Green
Lucas Green

Reputation: 3959

If you are looking to put the current page's URL into formfield, this is how it could be accomplished:

f.value = window.location;

Upvotes: 1

Related Questions