3

I am only able to fetch the value after HTML is finished loading by using this code:

var array = $('#Stats1_totalCount strong').map(function(){
    return $(this).text()
}).get();
var vcount = '';
for (i = 0; i < array.length; i++) { 
    vcount += array[i];
}
console.log(vcount);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="counter-wrapper graph-counter-wrapper" id="Stats1_totalCount">
  <span class="digit stage-0"><strong>1</strong></span>
  <span class="digit stage-0"><strong>2</strong></span>
  <span class="digit stage-0"><strong>3</strong></span>
  <span class="digit stage-0"><strong>4</strong></span>
  <span class="digit stage-0"><strong>5</strong></span>
</span>

But Blogger uses ajax to inject counter:

Counter and image will be injected later via AJAX call.

I tried using .ajaxStop and ajaxComplete, none of them works.
How can I get the view counter's value with JS?

Louis55
  • 408
  • 6
  • 17

1 Answers1

0

Thanks for @RoryMcCrossan' s suggestion using MutationObserver, I am now able to get view counter's value with JavaScript!

(function startObservation() {
  var
    /* 1) Create a MutationObserver object*/
    observer = new MutationObserver(
      function(mutations) {      
      mutationObserverCallback(mutations);
    }),  
    /* 2) Create a config object */
    config = {childList: true};
 
  /* 3) Glue'em all */
  observer.observe(Stats1_totalCount, config);
})();
function mutationObserverCallback(mutations) {
  var mutationRecord = mutations[0];
  if (mutationRecord.addedNodes[0] !== undefined) {

  var array = $('#Stats1_totalCount strong').map(function(){
    return $(this).text()
  }).get();
  var vcount = '';
  for (i = 0; i < array.length; i++) { 
    vcount += array[i];
  }
  console.log(vcount);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="counter-wrapper graph-counter-wrapper" id="Stats1_totalCount">
  <span class="digit stage-0"><strong>1</strong></span>
  <span class="digit stage-0"><strong>2</strong></span>
  <span class="digit stage-0"><strong>3</strong></span>
  <span class="digit stage-0"><strong>4</strong></span>
  <span class="digit stage-0"><strong>5</strong></span>
</span>
Louis55
  • 408
  • 6
  • 17