Search code examples
javascriptpolicy

How to set feature policy headers in JS


I am getting the following errors in my console on my site:

Error with Feature-Policy header: Unrecognized feature: 'unsized-media'.
Error with Feature-Policy header: Unrecognized feature: 'ambient-light-sensor'.
Error with Feature-Policy header: Unrecognized feature: 'speaker'.
Error with Feature-Policy header: Unrecognized feature: 'vr'.

I am a front end web developer so I'm trying to set this in JS as described here https://developers.google.com/web/updates/2018/06/feature-policy#js without messing with my server config.

console.log(document.featurePolicy.allowedFeatures());

results in:

["geolocation", "midi", "ch-ect", "usb", "magnetometer", "picture-in-picture", "publickey-credentials-get", "accelerometer", "ch-lang", "document-domain", "encrypted-media", "ch-downlink", "ch-ua-arch", "xr-spatial-tracking", "ch-ua-platform-version", "ch-width", "ch-ua-model", "sync-xhr", "camera", "ch-viewport-width", "payment", "ch-rtt", "ch-ua-full-version", "fullscreen", "autoplay", "ch-dpr", "ch-ua-platform", "screen-wake-lock", "gyroscope", "ch-ua-mobile", "ch-device-memory", "ch-ua", "microphone"]

Also

document.featurePolicy.allowsFeature('unsized-media', 'self');

results in:

Invalid origin url for feature 'unsized-media': self.

Solution

  • You can't.

    Feature policies are set by the server (via the Feature-Policy or Permissions-Policy headers) and control what JavaScript is allowed to do.

    It would be pointless if the JavaScript could grant itself permission to do anything it liked.