Get value of span text in Tampermonkey

2019-08-01 03:03发布

I am playing with Tampermonkey scripts in JS. I have a website that shows the user's location and timezone in UTC format.

<span class="optional-wrapper">
   <span class="UTCText"> ==$0
   <!-- react-text: 60 --> 
   " (UTC "
   <!-- /react-text -->
   <!-- react-text: 61 -->
   "+10:00" 
   <!-- /react-text -->
   <!-- react-text: 62 -->
   ") "
   <!-- /react-text -->
   </span>
</span>

I want to read the UTC timezone (UTC +10:00) and convert it into a time. I tried something like this but it doesn't work. Can someone point me in the right direction where i can learn about this?

function getTimeZone(UTCText){
document.getElementsByClassName(UTCText);
console.log(UTCText)
}

At the moment I just want to print to the console so I know I am reading the timezone correctly.

1条回答
We Are One
2楼-- · 2019-08-01 03:50

To get the text from a static page, use .textContent and then parse the string to extract the value you want.
Here's a demo:

var tzOffset    = "Not found!";
var tzNode      = document.querySelector (".UTCText");
if (tzNode) {
    let ndTxt   = tzNode.textContent;
    let tzMtch  = ndTxt.match (/(-?\d+:\d+)/);
    if (tzMtch  &&  tzMtch.length > 1) {
        tzOffset = tzMtch[1];
    }
}
console.log ("Found timezone offset: ", tzOffset);
<span class="optional-wrapper">
   <span class="UTCText"> ==$0
   <!-- react-text: 60 -->
   " (UTC "
   <!-- /react-text -->
   <!-- react-text: 61 -->
   "-10:30"
   <!-- /react-text -->
   <!-- react-text: 62 -->
   ") "
   <!-- /react-text -->
   </span>
</span>


However, that page looks to be using , which means it's AJAX-driven.

For AJAX'd pages, you often have to use AJAX-aware techniques such as waitForKeyElements. Here's what that looks like in a complete Tampermonkey userscript:

// ==UserScript==
// @name     _Get timezone offset text from a span
// @match    *://YOUR_SERVER.COM/YOUR_PATH/*
// @noframes
// @require  https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    GM_addStyle
// @grant    GM.getValue
// ==/UserScript==
// @grant    none
//- The @grant directives are needed to restore the proper sandbox.
/* global $, waitForKeyElements */
/* eslint-disable no-multi-spaces, curly */

waitForKeyElements (".UTCText", getTZ_Offset);

function getTZ_Offset (jNode) {
    var tzOffset    = "Not found!";
    let ndTxt       = jNode.text ();
    let tzMtch      = ndTxt.match (/(-?\d+:\d+)/);
    if (tzMtch  &&  tzMtch.length > 1) {
        tzOffset    = tzMtch[1];
    }
    console.log ("Found timezone offset: ", tzOffset);
}
查看更多
登录 后发表回答