Use a Worker thread together with WordPress Nonce (custom wp-api endpoint)











up vote
1
down vote

favorite












I'm building a plugin for WordPress which has to do a big pile of ajax requests to a custom WP API endpoint. The requests cannot be processed asynchronous, which makes it neccessary to use a Worker thread to prevent the browser from hanging during the process. So far not that complicated, but I want to use the WordPress nonce for verification. When I make a worker, I did it like this:



worker = new Worker("worker.js");


This loads the worker correctly, but now I want to talk to our custom Ajax endpoint. Therefore the script needs to be loaded through wp_enqueue_script so the nonce gets verified (am I correct here?).



wp_enqueue_script('itw_admin_update_products', plugins_url('assets/js/worker.js', __FILE__), [ 'jquery', 'wp-api' ], '1.0', true );


The above makes it off course load twice. How to load the script as a worker while still be able to verify the nonce at the Ajax endpoint?










share|improve this question







New contributor




Mike is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
























    up vote
    1
    down vote

    favorite












    I'm building a plugin for WordPress which has to do a big pile of ajax requests to a custom WP API endpoint. The requests cannot be processed asynchronous, which makes it neccessary to use a Worker thread to prevent the browser from hanging during the process. So far not that complicated, but I want to use the WordPress nonce for verification. When I make a worker, I did it like this:



    worker = new Worker("worker.js");


    This loads the worker correctly, but now I want to talk to our custom Ajax endpoint. Therefore the script needs to be loaded through wp_enqueue_script so the nonce gets verified (am I correct here?).



    wp_enqueue_script('itw_admin_update_products', plugins_url('assets/js/worker.js', __FILE__), [ 'jquery', 'wp-api' ], '1.0', true );


    The above makes it off course load twice. How to load the script as a worker while still be able to verify the nonce at the Ajax endpoint?










    share|improve this question







    New contributor




    Mike is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.






















      up vote
      1
      down vote

      favorite









      up vote
      1
      down vote

      favorite











      I'm building a plugin for WordPress which has to do a big pile of ajax requests to a custom WP API endpoint. The requests cannot be processed asynchronous, which makes it neccessary to use a Worker thread to prevent the browser from hanging during the process. So far not that complicated, but I want to use the WordPress nonce for verification. When I make a worker, I did it like this:



      worker = new Worker("worker.js");


      This loads the worker correctly, but now I want to talk to our custom Ajax endpoint. Therefore the script needs to be loaded through wp_enqueue_script so the nonce gets verified (am I correct here?).



      wp_enqueue_script('itw_admin_update_products', plugins_url('assets/js/worker.js', __FILE__), [ 'jquery', 'wp-api' ], '1.0', true );


      The above makes it off course load twice. How to load the script as a worker while still be able to verify the nonce at the Ajax endpoint?










      share|improve this question







      New contributor




      Mike is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      I'm building a plugin for WordPress which has to do a big pile of ajax requests to a custom WP API endpoint. The requests cannot be processed asynchronous, which makes it neccessary to use a Worker thread to prevent the browser from hanging during the process. So far not that complicated, but I want to use the WordPress nonce for verification. When I make a worker, I did it like this:



      worker = new Worker("worker.js");


      This loads the worker correctly, but now I want to talk to our custom Ajax endpoint. Therefore the script needs to be loaded through wp_enqueue_script so the nonce gets verified (am I correct here?).



      wp_enqueue_script('itw_admin_update_products', plugins_url('assets/js/worker.js', __FILE__), [ 'jquery', 'wp-api' ], '1.0', true );


      The above makes it off course load twice. How to load the script as a worker while still be able to verify the nonce at the Ajax endpoint?







      javascript wordpress wordpress-rest-api






      share|improve this question







      New contributor




      Mike is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      share|improve this question







      New contributor




      Mike is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      share|improve this question




      share|improve this question






      New contributor




      Mike is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked Nov 21 at 14:07









      Mike

      1062




      1062




      New contributor




      Mike is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      Mike is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      Mike is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          0
          down vote













          Just figured it out myself:



          Register a REST route



          register_rest_route('my-rest-route/v1', '/rest-action', array(
          'methods' => 'GET',
          'callback' => 'callback-function',
          'permission_callback' => function () { return current_user_can('edit_pages'); },


          Enqueue the scripts



          The wp_localize_script() function passes along the variables we need to load the worker and to tell where the worker should do the request. wp_enqueue_script() makes sure the script is loaded at the right moment and is allowed to do requests to the API endpoint.



          $params = array(
          'jsWorker' => plugins_url('assets/js/the-worker.js', ITW_BASEDIR . '/ipp-to-woo.php'),
          'rest_route' => get_rest_url(null, 'my-rest-route/v1/rest-action'),
          );
          wp_register_script('the_handler', plugins_url('assets/js/the-script.js', __FILE__), [ 'jquery', 'wp-api' ], '1.0', true );
          wp_localize_script('the_handler', 'the_object', $params);
          wp_enqueue_script('the_handler');


          call the worker from the-script.js



          Because we used wp_localize_script() to pass variables to the client side, we are now able to use the_object.jsWorker to load the worker. After loading the worker we pass along an object with worker.postMessage containing the API endpoint and the nonce generated by WordPress to verify ourselves.



          worker = new Worker(the_object.jsWorker);
          worker.addEventListener('message', function(e) {
          var response
          response = JSON.parse(e.data)

          processResponse(response);

          });

          worker.postMessage({'nonce': wpApiSettings.nonce, 'url': the_object.rest_route});


          Do an Ajax call from the-worker.js



          And last but not least, in the-worker.js we use xhr.setRequestHeader to verify ourselves like Wordpress does.



          function doAjaxCall(url, nonce){
          var xhr = new XMLHttpRequest();
          xhr.open('GET', url, false);
          xhr.setRequestHeader( 'X-WP-Nonce', nonce );
          xhr.onload = function() {
          if (xhr.status === 200) {
          self.postMessage(xhr.response);
          }
          };
          xhr.send();
          }

          self.addEventListener('message', function(e) {
          var data = e.data;
          self.doAjaxCall(data.url, data.nonce);
          }, false);





          share|improve this answer








          New contributor




          Mike is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.


















            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });






            Mike is a new contributor. Be nice, and check out our Code of Conduct.










             

            draft saved


            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53413883%2fuse-a-worker-thread-together-with-wordpress-nonce-custom-wp-api-endpoint%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            0
            down vote













            Just figured it out myself:



            Register a REST route



            register_rest_route('my-rest-route/v1', '/rest-action', array(
            'methods' => 'GET',
            'callback' => 'callback-function',
            'permission_callback' => function () { return current_user_can('edit_pages'); },


            Enqueue the scripts



            The wp_localize_script() function passes along the variables we need to load the worker and to tell where the worker should do the request. wp_enqueue_script() makes sure the script is loaded at the right moment and is allowed to do requests to the API endpoint.



            $params = array(
            'jsWorker' => plugins_url('assets/js/the-worker.js', ITW_BASEDIR . '/ipp-to-woo.php'),
            'rest_route' => get_rest_url(null, 'my-rest-route/v1/rest-action'),
            );
            wp_register_script('the_handler', plugins_url('assets/js/the-script.js', __FILE__), [ 'jquery', 'wp-api' ], '1.0', true );
            wp_localize_script('the_handler', 'the_object', $params);
            wp_enqueue_script('the_handler');


            call the worker from the-script.js



            Because we used wp_localize_script() to pass variables to the client side, we are now able to use the_object.jsWorker to load the worker. After loading the worker we pass along an object with worker.postMessage containing the API endpoint and the nonce generated by WordPress to verify ourselves.



            worker = new Worker(the_object.jsWorker);
            worker.addEventListener('message', function(e) {
            var response
            response = JSON.parse(e.data)

            processResponse(response);

            });

            worker.postMessage({'nonce': wpApiSettings.nonce, 'url': the_object.rest_route});


            Do an Ajax call from the-worker.js



            And last but not least, in the-worker.js we use xhr.setRequestHeader to verify ourselves like Wordpress does.



            function doAjaxCall(url, nonce){
            var xhr = new XMLHttpRequest();
            xhr.open('GET', url, false);
            xhr.setRequestHeader( 'X-WP-Nonce', nonce );
            xhr.onload = function() {
            if (xhr.status === 200) {
            self.postMessage(xhr.response);
            }
            };
            xhr.send();
            }

            self.addEventListener('message', function(e) {
            var data = e.data;
            self.doAjaxCall(data.url, data.nonce);
            }, false);





            share|improve this answer








            New contributor




            Mike is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.






















              up vote
              0
              down vote













              Just figured it out myself:



              Register a REST route



              register_rest_route('my-rest-route/v1', '/rest-action', array(
              'methods' => 'GET',
              'callback' => 'callback-function',
              'permission_callback' => function () { return current_user_can('edit_pages'); },


              Enqueue the scripts



              The wp_localize_script() function passes along the variables we need to load the worker and to tell where the worker should do the request. wp_enqueue_script() makes sure the script is loaded at the right moment and is allowed to do requests to the API endpoint.



              $params = array(
              'jsWorker' => plugins_url('assets/js/the-worker.js', ITW_BASEDIR . '/ipp-to-woo.php'),
              'rest_route' => get_rest_url(null, 'my-rest-route/v1/rest-action'),
              );
              wp_register_script('the_handler', plugins_url('assets/js/the-script.js', __FILE__), [ 'jquery', 'wp-api' ], '1.0', true );
              wp_localize_script('the_handler', 'the_object', $params);
              wp_enqueue_script('the_handler');


              call the worker from the-script.js



              Because we used wp_localize_script() to pass variables to the client side, we are now able to use the_object.jsWorker to load the worker. After loading the worker we pass along an object with worker.postMessage containing the API endpoint and the nonce generated by WordPress to verify ourselves.



              worker = new Worker(the_object.jsWorker);
              worker.addEventListener('message', function(e) {
              var response
              response = JSON.parse(e.data)

              processResponse(response);

              });

              worker.postMessage({'nonce': wpApiSettings.nonce, 'url': the_object.rest_route});


              Do an Ajax call from the-worker.js



              And last but not least, in the-worker.js we use xhr.setRequestHeader to verify ourselves like Wordpress does.



              function doAjaxCall(url, nonce){
              var xhr = new XMLHttpRequest();
              xhr.open('GET', url, false);
              xhr.setRequestHeader( 'X-WP-Nonce', nonce );
              xhr.onload = function() {
              if (xhr.status === 200) {
              self.postMessage(xhr.response);
              }
              };
              xhr.send();
              }

              self.addEventListener('message', function(e) {
              var data = e.data;
              self.doAjaxCall(data.url, data.nonce);
              }, false);





              share|improve this answer








              New contributor




              Mike is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
              Check out our Code of Conduct.




















                up vote
                0
                down vote










                up vote
                0
                down vote









                Just figured it out myself:



                Register a REST route



                register_rest_route('my-rest-route/v1', '/rest-action', array(
                'methods' => 'GET',
                'callback' => 'callback-function',
                'permission_callback' => function () { return current_user_can('edit_pages'); },


                Enqueue the scripts



                The wp_localize_script() function passes along the variables we need to load the worker and to tell where the worker should do the request. wp_enqueue_script() makes sure the script is loaded at the right moment and is allowed to do requests to the API endpoint.



                $params = array(
                'jsWorker' => plugins_url('assets/js/the-worker.js', ITW_BASEDIR . '/ipp-to-woo.php'),
                'rest_route' => get_rest_url(null, 'my-rest-route/v1/rest-action'),
                );
                wp_register_script('the_handler', plugins_url('assets/js/the-script.js', __FILE__), [ 'jquery', 'wp-api' ], '1.0', true );
                wp_localize_script('the_handler', 'the_object', $params);
                wp_enqueue_script('the_handler');


                call the worker from the-script.js



                Because we used wp_localize_script() to pass variables to the client side, we are now able to use the_object.jsWorker to load the worker. After loading the worker we pass along an object with worker.postMessage containing the API endpoint and the nonce generated by WordPress to verify ourselves.



                worker = new Worker(the_object.jsWorker);
                worker.addEventListener('message', function(e) {
                var response
                response = JSON.parse(e.data)

                processResponse(response);

                });

                worker.postMessage({'nonce': wpApiSettings.nonce, 'url': the_object.rest_route});


                Do an Ajax call from the-worker.js



                And last but not least, in the-worker.js we use xhr.setRequestHeader to verify ourselves like Wordpress does.



                function doAjaxCall(url, nonce){
                var xhr = new XMLHttpRequest();
                xhr.open('GET', url, false);
                xhr.setRequestHeader( 'X-WP-Nonce', nonce );
                xhr.onload = function() {
                if (xhr.status === 200) {
                self.postMessage(xhr.response);
                }
                };
                xhr.send();
                }

                self.addEventListener('message', function(e) {
                var data = e.data;
                self.doAjaxCall(data.url, data.nonce);
                }, false);





                share|improve this answer








                New contributor




                Mike is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.









                Just figured it out myself:



                Register a REST route



                register_rest_route('my-rest-route/v1', '/rest-action', array(
                'methods' => 'GET',
                'callback' => 'callback-function',
                'permission_callback' => function () { return current_user_can('edit_pages'); },


                Enqueue the scripts



                The wp_localize_script() function passes along the variables we need to load the worker and to tell where the worker should do the request. wp_enqueue_script() makes sure the script is loaded at the right moment and is allowed to do requests to the API endpoint.



                $params = array(
                'jsWorker' => plugins_url('assets/js/the-worker.js', ITW_BASEDIR . '/ipp-to-woo.php'),
                'rest_route' => get_rest_url(null, 'my-rest-route/v1/rest-action'),
                );
                wp_register_script('the_handler', plugins_url('assets/js/the-script.js', __FILE__), [ 'jquery', 'wp-api' ], '1.0', true );
                wp_localize_script('the_handler', 'the_object', $params);
                wp_enqueue_script('the_handler');


                call the worker from the-script.js



                Because we used wp_localize_script() to pass variables to the client side, we are now able to use the_object.jsWorker to load the worker. After loading the worker we pass along an object with worker.postMessage containing the API endpoint and the nonce generated by WordPress to verify ourselves.



                worker = new Worker(the_object.jsWorker);
                worker.addEventListener('message', function(e) {
                var response
                response = JSON.parse(e.data)

                processResponse(response);

                });

                worker.postMessage({'nonce': wpApiSettings.nonce, 'url': the_object.rest_route});


                Do an Ajax call from the-worker.js



                And last but not least, in the-worker.js we use xhr.setRequestHeader to verify ourselves like Wordpress does.



                function doAjaxCall(url, nonce){
                var xhr = new XMLHttpRequest();
                xhr.open('GET', url, false);
                xhr.setRequestHeader( 'X-WP-Nonce', nonce );
                xhr.onload = function() {
                if (xhr.status === 200) {
                self.postMessage(xhr.response);
                }
                };
                xhr.send();
                }

                self.addEventListener('message', function(e) {
                var data = e.data;
                self.doAjaxCall(data.url, data.nonce);
                }, false);






                share|improve this answer








                New contributor




                Mike is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.









                share|improve this answer



                share|improve this answer






                New contributor




                Mike is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.









                answered Nov 22 at 9:46









                Mike

                1062




                1062




                New contributor




                Mike is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.





                New contributor





                Mike is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.






                Mike is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.






















                    Mike is a new contributor. Be nice, and check out our Code of Conduct.










                     

                    draft saved


                    draft discarded


















                    Mike is a new contributor. Be nice, and check out our Code of Conduct.













                    Mike is a new contributor. Be nice, and check out our Code of Conduct.












                    Mike is a new contributor. Be nice, and check out our Code of Conduct.















                     


                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53413883%2fuse-a-worker-thread-together-with-wordpress-nonce-custom-wp-api-endpoint%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Contact image not getting when fetch all contact list from iPhone by CNContact

                    count number of partitions of a set with n elements into k subsets

                    A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks