Firefox 扩展无法发出 post 请求,但可以使用常规脚本标签
Firefox extenstions fails to make post request, but works with regular script tag
我正在尝试从我的 firefox 扩展发出 post 请求。我面临的问题是,当加载我的扩展脚本时,浏览器似乎甚至没有尝试发出 post 请求。
为了确保问题不在于代码本身,我创建了一个 index.html 文件,里面有一个脚本标签,然后将我的代码粘贴到那里,它就可以工作了。
我的扩展脚本文件(不工作)
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)
}
})
我的 index.html 文件(有效)
<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>
我的期望是 javascript 从扩展加载的行为应该与脚本标签的行为相同。我被困住了,感谢所有帮助。
我通过更新 manifest.json 文件中的 permissions 属性解决了这个问题。
这是我添加的"permissions": ["*://*/*"]
。它现在匹配 content_scripts 属性.
的匹配字段中的表达式
非常感谢@Titus 提供有关 manifest.json 文件的提示!
我正在尝试从我的 firefox 扩展发出 post 请求。我面临的问题是,当加载我的扩展脚本时,浏览器似乎甚至没有尝试发出 post 请求。
为了确保问题不在于代码本身,我创建了一个 index.html 文件,里面有一个脚本标签,然后将我的代码粘贴到那里,它就可以工作了。
我的扩展脚本文件(不工作)
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)
}
})
我的 index.html 文件(有效)
<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>
我的期望是 javascript 从扩展加载的行为应该与脚本标签的行为相同。我被困住了,感谢所有帮助。
我通过更新 manifest.json 文件中的 permissions 属性解决了这个问题。
这是我添加的"permissions": ["*://*/*"]
。它现在匹配 content_scripts 属性.
非常感谢@Titus 提供有关 manifest.json 文件的提示!