几件事:
- 推文是通过 AJAX 添加的,因此您需要使用支持 AJAX 的脚本。下面,我将展示如何使用waitForKeyElements() 实用程序来执行此操作。
- 不要使用
innerHTML
. 它会破坏事情(加上它更慢)。使用jQuery或“DOM 技术”(如下所示)。
.replace()
使用正则表达式来获取时间,因此不需要大量不同的语句。
综上所述,这是一个完整的工作脚本:
// ==UserScript==
// @name _PSO2 Emg Bot Script
// @namespace Twitter
// @description Convert time to EST
// @include https://twitter.com/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @require https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
introduced in GM 1.0. It restores the sandbox.
*/
waitForKeyElements ("p.js-tweet-text", ChangeSpecialTimeStrs);
function ChangeSpecialTimeStrs (jNode) {
var node = jNode[0];
//-- Search only in the first-level text nodes of this paragraph.
for (var K = 0, numC = node.childNodes.length; K < numC; ++K) {
var childNode = node.childNodes[K];
if (childNode.nodeType === Node.TEXT_NODE) {
if (childNode.nodeValue.length > 8) {
//-- Anything shorter can't have our kind of string.
childNode.nodeValue = childNode.nodeValue.replace (
/*-- This matches strings like: "5:00~15:30"
Where "~" may be unicode FF5E
*/
/\b(\d{1,2}):(\d{2})(?:~|\uFF5E)(\d{1,2}):(\d{2})\b/gi,
shiftHourStr
);
}
}
}
}
function shiftHourStr (
matchedStr, //- Housekeeping supplied by .replace()
hour1Str, minute1Str, //- Payload vals from () groups
hour2Str, minute2Str, //- Payload vals from () groups
matchOffset, totalString //- Housekeeping supplied by .replace()
) {
//-- Return a string with a format like: "12:00 A.M. ~ 12:30 A.M."
const tzOffsetHours = 10;
var newHr1Arry = getHourOffset (hour1Str, tzOffsetHours);
var newHr2Arry = getHourOffset (hour2Str, tzOffsetHours);
var outputStr = newHr1Arry[0] //-- Hour value
+ ":" + minute1Str
+ newHr1Arry[1] //-- AM or PM
+ " ~ "
+ newHr2Arry[0] //-- Hour value
+ ":" + minute2Str
+ newHr2Arry[1] //-- AM or PM
;
return outputStr;
};
function getHourOffset (hourVal, hoursOffset) {
var amPmStr = "A.M.";
var newHourVal = parseInt (hourVal, 10) + hoursOffset;
if (newHourVal > 23) {
newHourVal -= 24;
}
if (newHourVal >= 12) {
newHourVal -= 12;
amPmStr = "P.M.";
}
if (newHourVal == 0) {
newHourVal = 12;
amPmStr = "A.M.";
}
return [newHourVal, " " + amPmStr];
}