2016-11-26 67 views
3

我想知道一個不屬於我的站點上的某些DOM元素的所有更改,因此我可以接收有關DOM元素更改的瀏覽器通知。 如果我無法在網站上編寫代碼,我該如何做到這一點? 我想用這個辦法:我可以在不是我的網站上添加事件監聽器嗎?

// select the target node 
 
var target = document.getElementById('some-id'); 
 
    
 
// create an observer instance 
 
var observer = new MutationObserver(function(mutations) { 
 
    mutations.forEach(function(mutation) { 
 
    console.log(mutation.type); 
 
    });  
 
}); 
 
    
 
// configuration of the observer: 
 
var config = { attributes: true, childList: true, characterData: true }; 
 
    
 
// pass in the target node, as well as the observer options 
 
observer.observe(target, config); 
 
    
 
// later, you can stop observing 
 
observer.disconnect();
<div id="some-id"></div>

謝謝!

+0

如何將是這個其他網站上運行您的代碼? – vlaz

+0

這是我的問題。 – alwizo

+1

但你還沒有給我們任何工作。你想在某種瀏覽器插件中使用它嗎?你想讓它在每個用戶的機器上運行嗎?你只想要你的嗎?你的問題幾乎等同於「我該怎麼做」 - 是的,它可以得到回答,但需要澄清。 – vlaz

回答

1

可以客戶端代碼總是添加到任何網站。例如,這是瀏覽器擴展的主要行爲。

但你也可以直接把你的代碼並將其粘貼到瀏覽器的控制檯(鉻:按Ctrl + + ĴF12

在這個例子中,我們將obeserve的<div id="question-header">這個SO頁面。

// select the target node 
var target = document.getElementById('question-header'); 

// create an observer instance 
var observer = new MutationObserver(function(mutations) { 
    Notification.requestPermission(function (permission) { 
    if (permission === "granted") { 
     var notification = new Notification("Something has changed!"); 
    } 
    }); 
    mutations.forEach(function(mutation) { 
    console.log(mutation.type); 
    });  
}); 

// configuration of the observer: 
var config = { attributes: true, childList: true, characterData: true }; 

// pass in the target node, as well as the observer options 
observer.observe(target, config); 

然後執行此來測試它是否工作:

var node = document.createElement("b");     
var textnode = document.createTextNode("Hello new item"); 
node.appendChild(textnode); 
document.getElementById("question-header").appendChild(node); 
+0

謝謝!這正是我想知道的。 – alwizo

0

你可以做到這一點像這樣的東西:

$(function(){ 
    var keep = ''; 
    var ajaxurl = "http://foo.bar"; 

    setInterval(function(){ 
     $.get(ajaxurl, { sample_data : 'test' }, function(response){ 

      var log = "<p>Checked</p>"; 

      if(keep != '' && keep !== response) 
       log = "<p>Something has changed</p>"; 

       $('.log-container').append(log); 

     }); 

    }, 2000); 
}); 

但你可以做更高級的東西與pusherJS https://github.com/pusher/pusher-js

+1

如果我理解它會每隔2秒發送一個查詢,並檢查是否有更改。這很好,但是如果我可以在沒有查詢的情況下獲得有關DOM更改的通知,那會更好。無論如何,謝謝你,因爲這對我有用。 – alwizo

相關問題