skip to Main Content

I’ve been trying to write a custom JavaScript console for use at school where they block inspect, and I’ve gotten quite far, but my stringify method throws an error when I try to crawl an HTMLAnchorElement. I’ve narrowed it down to an Illegal invocation for trying to access properties of the prototype of document.createElement("a").

const x = document.createElement("a");
const y = Object.getPrototypeOf(x);
console.log(y["href"]);

This code throws the Illegal invocation. However, this

const y = HTMLAnchorElement;
console.log(y["href"]);

doesn’t. I’ve looked into the Object.getOwnPropertyDescriptor(Object.getPrototypeOf(document.createElement("a")), "href").get() and that seems to be the problem. Is there a fix (perhaps binding the this value)?

2

Answers


  1. In the second example it does not throw an exception because HTMLAnchorElement is a constructor, (thus a function), and functions don’t have a propery "href" thus this is undefined. On the first and third example you get an Illegal invocation error because as explained here the context is lost. You can look the link for more detail, but in short, as you probably suspected the function internally uses this, so when its called outside of the context, it throws an error.

    Is there a fix (perhaps binding the this value)?

    Yes, you can fix it binding the right context to it

    For example in your third example Object.getOwnPropertyDescriptor(Object.getPrototypeOf(document.createElement("a")), "href").get() the get seems to expect the element that was created as context, thus this works:

    let href = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(a = document.createElement("a")), "href").get.bind(a); // note that I set a to the newly created element and then binded it to the get function
    href() // no error, its an empty string as expected
    

    but its not always clear what is the expected context, so I don’t know what you are trying to acomplish but maybe its not the best way.

    Login or Signup to reply.
  2. However, this

    const y = HTMLAnchorElement;
    console.log(y["href"]);
    

    doesn’t.

    Because you’re looking for HTMLAnchorElement.prototype. HTMLAnchorElement["href"] just doesn’t exist.

    Is there a fix (perhaps binding the this value)?

    Yes, which is done by accessing the href property via the element itself, i.e. x["href"].

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search