我可以在不属于我的网站上添加事件监听器吗?

时间:2016-11-26 13:59:55

标签: javascript jquery

我想知道一个网站上某些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>

谢谢!

2 个答案:

答案 0 :(得分:1)

您始终可以将客户端代码添加到任何网站。例如,这是浏览器扩展的主要行为。

但您也可以将代码粘贴到浏览器的控制台(Chrome: Ctrl + Shift + J F12

在此示例中,我们将遵守此SO页面的<div id="question-header">

// 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);  

答案 1 :(得分: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

做更高级的事情