Content Security Policy: cannot load Mixpanel in Chrome extension

痞子三分冷 提交于 2019-12-05 10:14:57

The problem here is that Chrome doesn't allow extensions to load remote resources over plain HTTP; only HTTPS is allowed:

As man-in-the-middle attacks are both trivial and undetectable over HTTP, those [i.e., http:] origins will not be accepted.

Your mixpanel.js script attempts to load http://cdn.mxpnl.com/libs/mixpanel-2.2.min.js instead of the corresponding https: link. To fix this, simply change the line:

a.src=("https:"===e.location.protocol?"https:":"http:")+'//cdn.mxpnl.com/libs/mixpanel-2.2.min.js'

to:

a.src='https://cdn.mxpnl.com/libs/mixpanel-2.2.min.js'

It's currently loading the http: version because window.location.protocol is chrome-extension:, rather than https:. This change simply forces loading of the https: version always.

The above answer incomplete. You have to do one more thing.

Step 1: Adding HTTPS

Do what the other answer told you to do, change the mixpanel code, change http://cdn.mxpnl.com/libs/mixpanel-2-latest.min.js to https://cdn.mxpnl.com/libs/mixpanel-2-latest.min.js

Step 2: Modifying content security in your manifest.json

Update the content_security_policy property in your manifest.json: { ..., "content_security_policy": "script-src 'self' https://cdn.mxpnl.com/libs/mixpanel-2-latest.min.js; object-src 'self'", ... }

This relaxes the default content security policy.

Step 3 [optional]: Adding Google Analytics

If you also want Google Analytics as well, you can add it like this: { ..., "content_security_policy": "script-src 'self' https://ssl.google-analytics.com https://cdn.mxpnl.com/libs/mixpanel-2-latest.min.js; object-src 'self'", ... }

I learned how to do this from Google's own tutorial on how to add Google Analytics.

You could use this script to load mixpanel from custom url.

<script>
  window.MIXPANEL_CUSTOM_LIB_URL = 'lib/mixpanel/mixpanel.js';
</script>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!