获取data-timestamp属性的值

时间:2017-03-31 20:09:15

标签: javascript google-chrome-extension

在我的Chrome扩展程序中,我尝试通过内容脚本从页面获取信息(" data-timestamp":1490893300813的值),但结果显示'空&#39 ;.



//content script:

  var tsx = document.getElementsByClassName("date");    
  var i;
  const ts = new Array;
  for (i = 0; i < tsx.length; i++) {
    var ts[i] = tsx[i].getAttribute("data-timestamp");        	
    console.log("Timestamp" + i + ": " + ts[i]);
  }
&#13;
<!--source code from page:-->

<div class="thread">
        <span data-timestamp="1490893300813" class="date">
            <span class="absolute">Do, 30.03.2017, 19:01</span>
            <span class="relative"></span>
        </span>
</div>
&#13;
&#13;
&#13;

我还注意到,当我显示页面的源代码( Ctrl + U )时,data-timestamp属性是可见的,但它不可见在DevTools ......

1 个答案:

答案 0 :(得分:1)

您可以使用document.querySelector('.date')选择具有date类的元素。从那里,您可以获得element.dataset.timestamp来获取时间戳。

您的代码可能类似于:

//Get the timestamp as a number ( + is used to convert from a string to a number).
var timestamp = +document.querySelector('.date').dataset.timestamp;
console.log('Timestamp:', timestamp);

//Convert to a Date and display in ISO format for the UTC timezone.
var date = new Date(timestamp);
console.log(date.toISOString());
<div class="thread">
        <span data-timestamp="1490893300813" class="date">
            <span class="absolute">Do, 30.03.2017, 19:01</span>
            <span class="relative"></span>
        </span>
</div>