Magento 2 – Fix Cross-Origin Problem with Google Customer Reviews on Success Page

googlemagento2

We've recently implemented Google's Customer Review module into our success page.

However, the console bugs. It keeps telling me:

jquery.js:2998 Uncaught DOMException: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin "http://my-dev-domain.tld" from accessing a cross-origin frame.

I understand that this is a problem from CORS, and therefore I added the following to my .htaccess:
Header set Access-Control-Allow-Origin "*"

However, this also didn't worked. The error is still showing.

Deactivating FPC hasn't changed something.

I've learned that there's a fix for page-cache.js in future versions of Magento (> 2.1.5, see https://github.com/magento/magento2/pull/8005).

However, copying the new PR to the staging system doesn't resolve the error, it still bugs.

How could I now solve my problem?

Btw, this is the code I inject:

In head:

https://apis.google.com/js/platform.js?onload=renderOptIn

In body:

<script type="text/javascript">
  window.renderOptIn = function() {
    window.gapi.load('surveyoptin', function() {
      window.gapi.surveyoptin.render(
        {
          "merchant_id": "xxxxxxxxx",
          "order_id": "<?= $data['orderid']; ?>",
          "email": "<?= $data['email']; ?>",
          "delivery_country": "<?= $data['country_id']; ?>",
          "estimated_delivery_date": "<?= $data['delivery_date']; ?>"
        });
    });
  }
</script>

Basic:

  • we are on Magento 2.0.4
  • when trying to use my solution on a Magento 2.1.5 system nothing gets shown, nor is there an error in the console

Best Answer

If you are right and problem is CORS:

Use the following directives on your apache:

RewriteEngine On                  
RewriteCond %{REQUEST_METHOD} OPTIONS 
RewriteRule ^(.*)$ $1 [R=200,L]

Also add:

Header always set Access-Control-Allow-Origin "*"                   
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS"

While using CORS request, your server will be asked to answer to OPTIONS requests by your browser. If you do non condigure it for a correct answer, the "preflight" check will fail.

If it works you can restrict origins.

Hope it helps.