Request permissions from content script

Hi there! I would like to attach event handler in content script and request permissions inside it, but it seems permissions API isn’t defined for content scripts. Bug? Are there any other way I can achieve my goal in Firefox?

document.querySelector('#hhhhhh').addEventListener('click', () => {
	console.log(chrome.permissions);	// undefined
	console.log(browser.permissions);	// undefined
});

Sending a message to the background script should retain the annotation that lets you request permissions and other things that require “user interaction”.

Thank you for response. Can you please provide more details of how can I “retain the annotation” ? In my experiments attempt to request from background script ends with
Error: permissions.request may only be called from a user input handler

The permission must be handled from the background script.

Here is one method of doing it:

  • from content script send a message to background script runtime.sendMessage()
  • in background script listen for the message from content runtime.onMessage.addListener()
  • once message is received, handle the permission request in background script
  • from background script send the result to content script runtime.sendMessage()
  • in content script listen for the message from background runtime.onMessage.addListener()

@erosman I have created test add-on that implements your approach. Unfortunately, I see Error: permissions.request may only be called from a user input handler in add-on debug console when click on “click me to request permissions” button

Code:
background.js:

browser.runtime.onMessage.addListener(() => {
    browser.permissions.request({ permissions: ['clipboardRead']})
        .then(granted => console.log(granted));
});

content.js:

var btn = document.createElement('button');
btn.innerHTML = 'click me to request permissions';
btn.addEventListener('click', () => {
    browser.runtime.sendMessage({});
});
document.body.appendChild(btn);

manifest.json:

{
    "background":{
        "scripts":[
            "background.js"
        ]
    },
    "name":"Test Permissions in Firefox",
    "manifest_version":2,
    "optional_permissions": [ "clipboardRead" ],
    "permissions":[ "<all_urls>" ],
    "content_scripts": [
        {
          "matches": ["*://*.example.com/*"],
          "js": ["content.js"]
        }
      ],
    "version":"0.0.1"
}

Ah, I believe you’re actually running into https://bugzilla.mozilla.org/show_bug.cgi?id=1392624, as in the annotation is not properly sent when the message comes from a content script.

@freaktechnik indeed I think it’s what I experience, thank you for the link, following this bug, hope will be fixed soon