Reputation: 37
It's a Chrome Extension JS, i want to compare the DOM tree structure between DOM loaded and all these files loaded.Here I declare two variable first and then it will run into these 2 Listeners. But txt1 won't keep the value in the 1st listener, no matter declare it with var or window. So how can I keep the global value? Or can I bypass it in other ways?
function tw1(){
var treeWalker = document.createTreeWalker(document,NodeFilter.SHOW_ELEMENT,{ acceptNode: function(node) { return NodeFilter.FILTER_ACCEPT; } },false);
var ar = new Array();
var count=0;
while(treeWalker.nextNode()) {
ar[count]=treeWalker.currentNode.nodeName;
count++;
console.log(treeWalker.currentNode.nodeName);
}
var txt="";
for (var i=0;i<count;i++)
{
txt=txt+ar[i]+i+"\t";
}
//console.log(txt);
return txt;
}
function compare(str,str0)
{
if(str.indexOf(str0) == 0&& str0.indexOf(str) == 0)
{
return 0;
}
else
{
return 1;
}
}
window.txt1="";
window.txt2="";
document.addEventListener('DOMContentLoaded', function() {
window.txt1=tw1();
}, false);
window.addEventListener('load', function() {
window.txt2=tw1();
console.log(window.txt1);
console.log(window.txt2);
if(compare(window.txt1,window.txt2)!=0)
alert("This page is possibly malicious.");
}, false);
Upvotes: 0
Views: 391
Reputation: 55750
Simplest is adding a check condition
if(!window.txt1.length)
window.txt1=tw1();
Upvotes: 1