Tuesday, 19 February 2019

Using Only Single Quotes in a QuerySelector

I'm working with a Chrome Extension that uses querySelectors to scrape the DOM. The following querySelector properly returns my desired value (the last name in a full name) when entered into the Console:

document.querySelector('[data-bind="text: 
PersonName.fullName"]').textContent.slice(document.querySelector('[data- 
bind="text: PersonName.fullName"]').textContent.indexOf(" ")+1)

Within the Extension, however, these querySelectors are served up in a JSON object via an API, and the double-quotes cause a JSON parsing error. Is there an equivalent way to write the above query selector using only single quotes? Or to escape the double-quotes somehow such that JSON won't have an issue parsing it?

If you wish to test a potential answer, here's the HTML element that I'm attempting to scrape:

<span data-bind="text: PersonName.fullName">John Smith</span>

To add clarity - I don't have control over the HTML page, it is on the end user's machine.

Here's the generated JSON:

{"AtsMapping":[{"ID":"4"},{"atsCode":"ULT1"},{"atsName":"UltiPro"}, 
{"atsMapName":"UltiPro"},{"atsMapNotes":"John Smith (1)"}, 
{"firstName":"document.querySelector('[data-bind="text: 
PersonName.fullName"]').textContent.slice(0,document.querySelector('[data- 
bind="text: PersonName.fullName"]').textContent.indexOf(" "))"}, 
{"lastName":"document.querySelector('[data-bind="text: 
PersonName.fullName"]').textContent.slice(document.querySelector('[data- 
bind="text: PersonName.fullName"]').textContent.indexOf(" ")+1)"}, 
{"emailAddress":"document.querySelector(".email-address").innerText;"}, 
{"jobTitle":"document.querySelector('[data-bind="text: 
OpportunityTitle"]').textContent"},{"location":""},{"locationDefault":""}, 
{"effectiveDate":""},{"effectiveDateDefault":""},{"expirationDate":""}, 
{"expirationDateDefault":""},{"flsaStatus":""},{"flsaStatusDefault":""}, 
{"compGroup":""},{"compGroupDefault":""},{"benefitsGroup":""}, 
{"benefitsGroupDefault":""},{"offerTemplate":""},{"offerTemplateDefault":""}, 
{"confidentialFlag":""},{"confidentialFlagDefault":""}]}

And the error in parsing this JSON is:

Uncaught SyntaxError: Unexpected token t in JSON at position 184 at JSON.parse () at Object.$.get [as success] (inject.js:10390) at fire (inject.js:3274) at Object.fireWith [as resolveWith] (inject.js:3404) at done (inject.js:9311) at XMLHttpRequest. (inject.js:9554)

Thanks!



from Using Only Single Quotes in a QuerySelector

No comments:

Post a Comment