Q:

Scraping DOM Values in a Chrome Extension

I'm scraping a user's page with a Chrome Extension. The Extension receives an API response which contains the proper document.querySelector(x) commands. It then attempts to locate that element, trim its innerText property, or grab its value property:
 //I've removed some additional fields here to focus on the one I'm currently testing
 message = {
  txtFName: {
    selector: fieldmap.AtsMapping[5].firstName,
    value: null
  }

  //line 10450 is the one below
  console.log(fieldmap.AtsMapping[5].firstName);

  Object.keys(message).forEach((key) => {
    const el = message[key].selector;

    if (el) {
       console.log("Exists in DOM")
        if(el.innerText && el.innerText.length > 0) {
           console.log("Has inner text property");
        message[key].value = el.innerText.trim();
        }
        else {
            console.log("Doesnt have inner text");
        message[key].value = el.value;
        }
    }
  });

Notice that my console:

Displays the querySelector from the API response
Can't locate the element in the DOM (i.e. console doesn't say "Exists in DOM")
But when I type the identical command with .innerText appended, I get "Jane",          the proper value.

My guess is that the API response, a JSON object, isn't properly being understood as JavaScript. But I'm not sure how to convert it.

A:

You have a string with the value "document.querySelector('#txtFName')" rather than an actual function call. You'd have to use eval or similar features.
eval:
const el = eval(message[key].selector);
Disclaimer: These features are usually not recommended because of security risks. For example, if some of the string originates from user input, a malicious attacker would be able to inject arbitrary code which could then be run on other users' browsers. If this is the only viable solution you should sanitize the inputs.
I will also mention this alternative for completeness. Function constructor may be used to create a new function with a string as the body. This has the same security risks as eval.

