4

I am trying to create a bookmarklet that will insert some text in a textarea on a webpage (webpage is for internal use so no point in linking).

Here is example of javascript code i tried:

(function(){document.getElementById("textareaID").value="Some text";})();

I'd like to point out that i tried different element selectors (byClass, query...) and different attributes (even tabindex) to the same result. Also tried in both Chrome and IE11.

So, for some weird reason my javascript runs when i run it from console (or as a snippet) but i get an error "Cannot set property 'value' of null" when i try to run it from bookmark menu.

I tried creating a bookmarklet by myself

javascript:(function(){document.getElementById("textareaID").value="Some text";})();

and tried using online bookmarklet creators to encode special characters

javascript:(function(){document.getElementById(%22textareaID%22).value=%22Some%20text%22;})();

but no luck.

Bookmarklets definitely work on a page (tried with alert "Hello") but i seem to have a problem "capturing" elements. Also i noticed that ID's of some elements change sometimes (not sure why though), but i always inspect to make sure that ID i try to use exists or i use some fixed value like tabindex. Besides, as i said it works when run from console, so i couldn't have screwed it up somehow... or could have i?

Frakula
  • 145
  • 10
  • Is page with the textarea open and loaded when you run this? – charlietfl Aug 07 '18 at 09:46
  • Could you try to run this `javascript:console.log(document.querySelector('*'))` and see if it logs anything in the console? – Olian04 Aug 07 '18 at 09:47
  • Yes, page with textarea is open and active, so i assume its fully loaded. When i run console.log code from bookmarklet it does log to console (i assume its entire html document). – Frakula Aug 07 '18 at 09:54

1 Answers1

4

So the problem was execution context. Because IDs of elements were changing i had to inspect them before running js from console and inspecting changes the execution context from top to wherever the element is. That's why it was working from console and not from bookmark...

So, to write into a textbox inside specific frame:

let Iframe =  document.getElementById('yourIframe').contentWindow.document
let value = Iframe.getElementById("textboxID").value = "Some Text"

After that only thing left is to wrap everything inside a javascript:(function(){..your code here..})(); to create a bookmarklet.

Frakula
  • 145
  • 10
  • 1
    Aahhhh it is the `.contentWindow.document` part that I'm missing!!! You are a saint for posting the answer to your own question. – Nate Mar 13 '20 at 18:48