Search code examples
javascriptinternet-explorercontextmenu

Accessing DOM via JS from internet explorer contextmenu


I want to manipulate DOM via javascript from the context menu of Internet Explorer. To do this, I created the key in registry as:

[HKEY_CURRENT_USER\SOFTWARE\Microsoft\Internet Explorer\MenuExt\Remove Node]
@="javascript:var d=document,h=d.head,b=d.body,css='<style>tr{border:solid 1px red;}</style>';h.innerHTML.indexOf(css)==-1?h.innerHTML+=css:h.innerHTML=h.innerHTML.replace(css,'');b.addEventListener('mousedown',function(c){var t=c.target;if(c.ctrlKey){c.preventDefault();t.style.display='none';}});void(0);"
"Contexts"=dword:00000001

But it didn't work with the error like: "document reference is undefined or empty". Then I tried more simple such as alert('something') which properly appeared as "something". I also tried more simple DOM reference, such as alert(document.title) returned empty.

How can I access a DOM element from context menu of Internet Explorer?

Thanks in advance.


Solution

  • Ok, I figured out the problem myself by using an external html file instead javascript URI. If someone needs it, they should do like this:

    [HKEY_CURRENT_USER\SOFTWARE\Microsoft\Internet Explorer\MenuExt\Remove Node]
    @="c:\path\to\the_html_file.html"
    "Contexts"=dword:00000001
    

    And the the_html_file.html file:

    <html>
    <script language="javascript" defer>
    var docment=window.external.menuArguments.document;
    // now it works!
    alert(docment.title);
    </script>
    </html>
    

    For more information: Adding Entries to the Standard Context Menu