0

我想在 facebook 页面上执行一个篡改猴子脚本,它定期轮询数据库以获取数据并执行一些操作。我尝试使用 ajax 实现轮询,下面是它的代码

(function poll() {
    setTimeout(function() {
           $.ajax({
                  url: "xyz",
                  headers: {
                  'Content-Type': 'application/json',
                  'x-apikey': apiKey,
                  'cache-control': 'no-cache'
                  },
                  type: "GET",
                  success: function(data) {

                  // check if null return (no results from API)
                  if (data == null) {
                        console.log('no data!');
                  } else {
                        console.log(data);                                          
                  },
                  dataType: "json",
                  complete: poll,
                  timeout: 2000
                  });
           }, 3000);
    })();

但是当我执行脚本时,出现以下错误

拒绝连接到“xyz”,因为它违反了以下内容安全策略指令:“connect-src *.facebook.com facebook.com *.fbcdn.net *.facebook.net .spotilocal.com: .akamaihd.net wss: // .facebook.com:* https://fb.scanandcleanlocal.com :* .atlassolutions.com attachment.fbsbx.com ws://localhost: blob: *.cdninstagram.com 'self' chrome-extension:// boadgeojelhgndaghljhdicfkmllpafd chrome-extension://dliochdbjfkdbacpmhlcpmleaejidimm"。

我了解该错误是由于 facebook 定义的内容安全策略指令。

有什么方法可以实现轮询?我还检查了油脂猴子 GM.xmlHttpRequest,但除了使用 ajax 之外,我找不到实现轮询的方法。

如果有人可以提供帮助,我将不胜感激

4

1 回答 1

1

我认为您收到的错误与跨域策略有关。Greasemonkey/Tampermonkey 用户脚本的GM_xmlhttpRequest工作跨域,所以你需要使用GM_xmlhttpRequest而不是$.ajax. 我已经尝试在GM_xmlhttpRequest公式中重写您的上述代码,因此您可以了解它的翻译方式:

var pollTimer = setInterval(function() {
     try {
          GM_xmlhttpRequest({
               method: "GET",
               url: "xyz",
               headers: {'Content-Type': "application/json",
                         'x-apikey':apiKey,
                         'cache-control': "no-cache"},
               onload: function(data){
                    // check if null return (no results from API)
                    if (data === null) {  // <-- note that you should use === rather than == for checking against null
                        console.log('no data!');
                    } else {
                        console.log(data); // if data in json format, will instead need console.log(JSON.stringify(data)) here
                    }
               },
               onerror: function(err) {
                   console.log('crap!  an error! ' + err);
               }
         });
         if (some condition exists that you would like polling to stop) {
             clearInterval(pollTimer);
         }
    } catch(e) {};
}, 3000);  // check every 3000 milliseconds
于 2018-03-26T20:05:11.963 回答