Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

改為即時更新, 在頁面有變動的時候就更新 #2

Merged
merged 1 commit into from Aug 27, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
50 changes: 37 additions & 13 deletions myscript.js
@@ -1,19 +1,40 @@
var interval = 5000;
var isEnabled = true;
var timer = null;

function change(node){
var key;
var p = node;
while( p && p!=document.body ){
if( p.isContentEditable )
return;
p = p.parentNode;
}
if( node.nodeName === '#text' ){
for(key in dict)
node.data = node.data.replace(new RegExp(key, 'g'), dict[key]);
}
else{
for(key in dict){
findAndReplaceDOMText(node, {
find: new RegExp(key, "g"),
replace: dict[key]
});
}
}
}

// https://github.com/padolsey/findAndReplaceDOMText
function change(){
for(var key in dict){
findAndReplaceDOMText(document, {
find: new RegExp(key, "g"),
replace: dict[key]
});
}
//console.log('run..');
setTimeout(change, interval);
function each(arr, act){
var i;
for(i=0; i<arr.length; ++i)
act(arr[i]);
}

var observer = new MutationObserver(function(mutations){
each(mutations, function(mutation){
each(mutation.addedNodes, change);
});
});

// 跟 background 互通
function setListener(){

Expand All @@ -28,15 +49,18 @@ function setListener(){
// 剛開始是關閉的,現在要啟動
if(window.firstEnabled===false && isEnabled){
window.firstEnabled = true
change();
change(document.body);
observer.observe(document.body, {childList:true, subtree:true});
}
return;
}

if(isEnabled){
change();
change(document.body);
observer.observe(document.body, {childList:true, subtree:true});
}else{
window.firstEnabled = false;
observer.disconnect();
}
});
}
Expand Down