Search code examples
javascriptjqueryapplescriptshadow-dom

Select shadow div text from page


I have an AppleScript I wrote that gets some information from a webpage (that's not mine), but the page has recently updated so that a value I need is in the shadow DOM, and not the main DOM (as shown in the Safari's Web Inspector). Before, I was using this AppleScript to retrieve the value:

set dateText to (do JavaScript "$('input#release_week').attr('value')" in doc) as string

With this being the operative JavaScript (using jQuery because the target page does):

$('input#release_week').attr('value')

Since the evaluated DOM now looks like this:

...
<input id="release_week" type="text" value="02/02/2022">
    <!-- Shadow Content (User Agent)
    <div contenteditable="plaintext-only">12/08/2021</div>
    -->
</input>
...

I'm always getting back the 02/02/2022 value, when I want the inner 12/08/2021 value instead. I've tried different variations, using the .shadowRoot property, and the >>> "shadow-piercing descending descendant combinator", neither of which worked.

What new JavaScript code can I use? The text I'm looking for is shown and selectable on the page, so I'm hopeful there has to be a way to get to it.

Update 2/3/22

This is the page I'm trying to get the date from, and this is the page element I'm trying to read the text from (at the top of the page), which doesn't match the <input>'s value after you click one of the arrows:

Date on page


Solution

  • It's not related to shadow DOM. Following elements are maintaining the value:

    <input id="date_release_week" type="text" name="date_release_week" class="filter-options-date date-pick dp-applied hasDatepicker" maxlength="255" autocomplete="off" value="02/02/2022">
    <input id="date_begin" type="hidden" name="date_begin" class="filter-options-date-begin" maxlength="255" autocomplete="off" value="02/02/2022">
    <input id="date_begin" type="hidden" name="date_begin" class="filter-options-date-begin" maxlength="255" autocomplete="off" value="02/03/2022">
    

    In devtool console if you run one of the following you'll get the actual selected date value:

    date_release_week.value
    date_begin[0].value
    date_begin[1].value
    

    Also, in Jquery, use val() function to get input value:

    $('input#date_release_week').change(() => {
      console.log('attr(\'val\'): ' + $('input#date_release_week').attr('value'));
      
      console.log('val(): ' + $('input#date_release_week').val());
    
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    Type something and press enter.
    <input type="text" id="date_release_week" name="name" required minlength="4" maxlength="8" size="10" value='add'>