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












1














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



























    1














    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

























      1












      1








      1







      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













      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













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 21 '18 at 14:07









      MikeMike

      1062




      1062
























          1 Answer
          1






          active

          oldest

          votes


















          0














          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





















            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',
            autoActivateHeartbeat: false,
            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
            });


            }
            });














            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









            0














            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


























              0














              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
























                0












                0








                0






                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












                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












                share|improve this answer



                share|improve this answer










                answered Nov 22 '18 at 9:46









                MikeMike

                1062




                1062






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    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

                    Wiesbaden

                    Marschland

                    Dieringhausen