根据这篇文章使用用户脚本记录网页的动态创建的标签属性
我检索了属性,还按照建议包括了数组
addJS_Node ("var arr=[];");
我成功地将 src 属性推送到 arr 数组,因为我没有收到任何错误。
现在我很困惑在哪里显示数组。
我的代码如下
// ==UserScript==
// @name Tags Monitoring
// @namespace PC
// @run-at document-start
// ==/UserScript==
//--- Intercept and log document.createElement().tagattributes
addJS_Node ("var arr=[];");
function LogNewTagCreations ()
{
var oldDocumentCreateElement = document.createElement;
document.createElement = function (tagName)
{
var elem = oldDocumentCreateElement.apply (document, arguments);
if(tagName=='script')
GetScriptAttributes (elem);
return elem;
}
}
function GetScriptAttributes (elem, tagNum, timerIntVar)
{
/*--- Because the tags won't be set for some while, we need
to poll for when they are added.
*/
GetScriptAttributes.tagNum = GetScriptAttributes.tagNum || 0;
if ( ! tagNum)
{
GetScriptAttributes.tagNum++;
tagNum = GetScriptAttributes.tagNum;
}
/*-- Getting the required attributes */
if (elem.src)
{
doneWaiting ();
arr.push(elem.src);
console.log (
tagNum," has a src attribute of:", elem.src,"=========",arr.length
);
}
else
{
if ( ! timerIntVar)
{
var timerIntVar = setInterval
(
function ()
{
GetScriptAttributes (elem, tagNum, timerIntVar);
},
50
);
}
}
function doneWaiting ()
{
if (timerIntVar)
{
clearInterval (timerIntVar);
}
}
}
/*--- The userscript or GM script will start running before the DOM is available.
Therefore, we wait...
*/
var waitForDomInterval = setInterval (
function () {
var domPresentNode;
if (typeof document.head == "undefined")
domPresentNode = document.querySelector ("head, body");
else
domPresentNode = document.head;
if (domPresentNode) {
clearInterval (waitForDomInterval);
addJS_Node (GetScriptAttributes.toString() );
addJS_Node (null, null, LogNewTagCreations);
}
},
1
);
addJS_Node("document.onreadystatechange = function (){if (document.readyState == 'complete'){console.log(arr.length);}}");
//--- Handy injection function.
function addJS_Node (text, s_URL, funcToRun) {
var D = document;
var scriptNode = D.createElement ('script');
scriptNode.type = "text/javascript";
if (text) scriptNode.textContent = text;
if (s_URL) scriptNode.src = s_URL;
if (funcToRun) scriptNode.textContent = '(' + funcToRun.toString() + ')()';
var targ = D.getElementsByTagName ('head')[0] || D.body || D.documentElement;
targ.appendChild (scriptNode);
}
我想打印动态创建的标签数量,这就是我添加数组的原因。我第一次尝试只使用脚本标签,我怎么知道数组已完成,以便我可以打印数组长度