Search code examples
javascriptxmlhttprequestfirefox-addon

Firefox extenstions fails to make post request, but works with regular script tag


I am trying to make a post request from my firefox extension. The issue I am facing is that the browser does not even seem to try and make the post request when the script for my extension is loaded.

To make sure that issue was not with the code itself I created a index.html file with a script tag in it and paste my code there and it works.

My extension script file (does not work)

console.log('loaded script')
this.addEventListener('keypress', (e) => {
    if (e.key === 'a') {
        const url = 'my-server-endpoint'
        var selectedText = window.getSelection().toString()
        var xhttp = new XMLHttpRequest()
        xhttp.open('POST', url, true)
        xhttp.setRequestHeader('Content-Type', 'text/plain')
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                console.log(JSON.parse(xhttp.response).url)
            }
        }
        xhttp.send(selectedText)
    }
})

My index.html file (does work)

<html>
    <head>
        <meta charset="utf-8">
    </head>
    Some sample text
    <script>
    this.addEventListener('keypress', (e) => {
        if (e.key === 'a') {
            const url = 'my-server-endpoint'
            var selectedText = window.getSelection().toString()
            var xhttp = new XMLHttpRequest()
            xhttp.open('POST', url, true)
            xhttp.setRequestHeader('Content-Type', 'text/plain')
            xhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    console.log(JSON.parse(xhttp.response).url)
                }
            }
            xhttp.send(selectedText)
        }
    })
    </script>
</html>

My expectations is that the javascript loaded from the extensions should behave in the same way the script tag does. I am stuck and all help is appreciated.


Solution

  • I solved this by updating my the permissions propety in my manifest.json file.

    Here is what I added "permissions": ["*://*/*"]. It now matches the expression in the matches field of the content_scripts property.

    Big thanks to @Titus for the hint about the manifest.json file!