WordPress REST API – Post Call from a Chrome Extension

I developed a chrome extension and I want to store some datas coming from the chrome extension to my wordpress website using REST API.

I have to 2 issues :

1- The first one is that I have an error linked to the fact that there is an interaction between two different domain : “Access to XMLHttpRequest at ‘https://groupio.fr/wp-json/groupio/v1/ean/‘ from origin ‘chrome-extension://hafjgepbbnbjcmmkealkikdjlmojdlkf’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: The ‘Access-Control-Allow-Origin’ header contains the invalid value ”.”

2- The second one is that I cannot return value to my chrome extension after running a php function from my WordPress website.

Here is my REST API call from the background.js file of my Chrome Extension :

chrome.runtime.onMessage.addListener(function(response, sender, sendResponse){

jQuery.ajax({

type:”POST”,
url: “https://groupio.fr/wp-json/groupio/v1/ean/”,
contentType: ‘applcation/json’,

data : {
ean: “1234567889”,
type: “Product Code”
},

success:function(data){

alert(data);
},

error: function(errorThrown){
console.log(errorThrown);
}
});

});

Here is my new endpoint and Rest API callback function inside the function.php of my theme
(as you can see I only want to return the exact value without processing anything) – and it does not work :

function my_awesome_func( $data ) {

return $data[‘ean’];
}

add_action( ‘rest_api_init’, function () {
register_rest_route( ‘groupio/v1’, ‘/ean/’, array(
‘methods’ => ‘POST’,
‘callback’ => ‘my_awesome_func’,
) );
} );

Thank you very much for your help – I will be very reactive to test your suggestions.

Read more here:: WordPress REST API – Post Call from a Chrome Extension

Leave a Reply

Your email address will not be published. Required fields are marked *