Create a polling feature using a Grease Monkey script

I am looking for a way to run a Tamper Monkey script on a Facebook page that regularly checks a database for new data and performs certain actions. I have attempted to implement polling using AJAX, and below is the code I used:

(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);
    })();

However, when I try to execute the script, I encounter the following error:

Refused to connect to 'xyz' because it violates the following Content Security Policy directive: "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".

I understand that this error is due to the content security policy directive set by Facebook.

Is there an alternative approach I can take to implement polling? I looked into Grease Monkey's GM.xmlHttpRequest but couldn't figure out how to do polling without using AJAX.

Any help would be greatly appreciated.

Answer №1

It seems like the issue you're encountering could be due to cross-domain policies. When using Greasemonkey/Tampermonkey userscripts, the GM_xmlhttpRequest function is necessary for making cross-domain requests instead of $.ajax. Below is a modified version of your code using 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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The JSON data script is not functioning properly

Is this JSON formatted correctly? Why is it not displaying in the element with #id? I found a similar code snippet on https://www.sitepoint.com/colors-json-example/, copied and replaced the values but it's not functioning. Can anyone shed some light o ...

The CSS transition will only activate when coupled with a `setTimeout` function

After using JavaScript to adjust the opacity of an element from 0 to 1, I expected it to instantly disappear and then slowly fade back in. However, nothing seems to happen as anticipated. Interestingly, if I insert a setTimeout function before applying th ...

Passing a message from a Struts2 action to jQuery

When using jQuery Ajax to call a Struts2 action, I have the following setup: $.ajax ({ url: 'callAction.action', type: 'POST', data: data, dataType: 'string', success: function (data ...

There are no leaks displayed in Chrome Dev Tools, however, the Task Manager will show them until Chrome eventually crashes

Do you have a CPU-intensive application that you're working on? Check it out here: https://codepen.io/team/amcharts/pen/47c41af971fe467b8b41f29be7ed1880 It involves a Canvas on which various elements are constantly being drawn. Here's the HTML ...

Implementing a sleek show/hide transition using slideToggle in jQuery

Trying to implement show/hide content with slideToggle and it's functioning, but the animation effect on the table is not smooth. Attempted two different codes, but none provided the desired animation effect: $('.more').slideToggle(' ...

Uncovering the "parent having two child elements" structure from HTML: A guide

I want to identify all parents with two children in an HTML document. Case 1 <parent> <child> <tag></tag> </child> <child></child> </parent> Case 2 <parent> <parent_and_child> <tag& ...

Is Same Origin Policy only enforced in incognito mode while utilizing Ajax?

When I attempt to use ajax to communicate with my server from a device, I encounter an issue. If I access the website in incognito mode, the service fails to work and logs the error message: Cross-Origin Request Blocked: The Same Origin Policy disallows ...

Begin the jQuery ResponsiveSlides Slider with the final image in the <ul> list

Currently utilizing the responsiveSlides image slider from responsiveSlides on our website. This jQuery slider uses an HTML unordered list of images to slide through automatically. The issue I'm facing is that before the slider actually starts (meani ...

Firefox 3 fails to utilize cache when an ajax request is made while the page is loading

Upon loading the page DOM, I utilize jQuery to fetch JSON data via ajax like so: $(document).ready(function(){ getData(); }); ...where the function getData() executes a basic jQuery ajax call similar to this: function getData(){ $.ajax({cache: t ...

Extracting the magnifying glass from the picture

After implementing a function to add a magnifying glass (.img-magnifier-glass) on button click, I am now looking to remove the glass by clicking the "cancel" button. However, I am unsure of how to write this function to interact with the "magnify" function ...

Error: Attempting to access a property called 'name' on an undefined variable leads to a TypeError

I am a beginner with MongodB and nodejs. I have successfully implemented the GET method, which returns an empty array. However, when I tried to use POST in Postman for "categories," I encountered this error message: ExpressJS categories route app.js Err ...

Is MapView in React Native restricted to explicit markers only?

I'm facing a challenging problem while working on my app's mapview. I have been struggling to find a solution for dynamically repopulating the mapview. Initially, I attempted the following approach: render() { const dynamicMarker = (lat, long, ...

"Upon clicking the commandButton with the bootsfaces iconAwesome, an Uncaught TypeError is triggered due to the inability to read the 'id' property

Whenever I click on a b:commandButton with an iconAwesome, the following error occurs: bsf.js.xhtml?ln=bsf:7 Uncaught TypeError: Cannot read property 'id' of nullBsF.ajax.onevent @ bsf.js.xhtml?ln=bsfsendEvent @ jsf.js.xhtml?ln=javax.faces:1 ...

Remove the initial section of the text and provide the rest of the string

I am a beginner in the world of Javascript and unfortunately I have not been able to find an answer to my current problem. Here is the situation. On a webpage, I am receiving a URL that is sometimes presented in this format: http://url1.come/http://url2.c ...

Producing asynchronous JavaScript events using a browser extension (NPAPI)

Currently in the process of developing a web browser plugin using NPAPI. The issue I am facing is that my plugin requires a worker thread to handle certain tasks, and I need to pass events back to JavaScript as the worker progresses. However, due to the N ...

Maximizing the potential of typescript generics in Reactjs functional components

I have a component within my react project that looks like this: import "./styles.css"; type InputType = "input" | "textarea"; interface ContainerProps { name: string; placeholder: string; as: InputType; } const Conta ...

Encountering the error "Cannot GET /login" while attempting to send a file through a post request in Express.js

I'm having trouble sending a new HTML file to the user after a successful login. Every time I attempt to send the file, I keep getting an error message saying "Cannot GET /login" on the page. Below is the section of code that's causing me diffic ...

How can I utilize JavaScript to generate a dynamic value in a URL and then submit it through a form?

One of my clients has requested the ability to send out unique URLs to their customers in order to track which links are being utilized. Despite my suggestion to use Google Analytics for this purpose, they have specifically asked to avoid it. Their reques ...

Determining Cost Using Quantity and Option Changes in Angular 4

Task In the shopping cart, there is a list of items with options, quantities, and prices. The goal is to calculate the total price based on any changes in the quantity and option of an item. Investigation I included [(ngModel)] for 2-way data binding, ...

Clicking on the title link will open the content in an iframe, but the image

Having trouble with a previous post but I've created a codepen to illustrate the issue. Hoping someone can help me out! Check out the codepen here: "https://codepen.io/Lossmann/pen/GRrXyQY" ...