用油脂猴子脚本实施民意调查

时间:2018-03-25 15:48:30

标签: javascript ajax xmlhttprequest polling greasemonkey-4

我想在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之外我找不到实现轮询的方法。

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

1 个答案:

答案 0 :(得分:1)

我认为您收到的错误与跨域政策有关。 Greasemonkey / Tampermonkey userscripts' 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