Chrome.tabs.captureVisibleTab总是失败,直到我点击弹出窗口

des4xlb0  于 12个月前  发布在  Go
关注(0)|答案(1)|浏览(295)

Chrome.tabs.captureVisibleTab()总是返回失败的消息,直到我点击弹出窗口。
在后台的错误信息中,它说:
错误:需要“<all_urls>”或“activeTab”权限。
实际上,我添加了“activeTab”权限。
奇怪的是,点击弹出页面后,一切都很好。
content_script.js:

let btn = document.createElement("button")
btn.innerText="screen cap"
document.body.appendChild(btn)

btn.onclick=(e)=>{
chrome.runtime.sendMessage({purpose:"screenCap"})
}

chrome.runtime.onMessage.addListener((msg)=>{
    if(msg.purpose  && msg.purpose==="screenCap" ){
        if(msg.status) {
            console.log(msg.data)
        }
        else{
            console.log("screen cap failed")
        }
    }
})

字符串
background.js

chrome.runtime.onMessage.addListener(
(msg)=>{
if(msg.purpose && msg.purpose === "screenCap"){
   chrome.tabs.captureVisibleTab().then(
(data)=>{  }
)
}
}
)


manifest.json

{
    "manifest_version": 3,
    "name": "screen cap test",
    "version": "1.0.1",
    "action": { "default_popup": "popup.html" },
    "content_scripts": [{
        "js": [
            "content.js"
        ],
        "matches": [
            "http://*/*", "https://*/*"
        ]
    }],
    "background": {
        "service_worker": "background.js",
        "persistent": true
    },

    "externally_connectable": {
        "matches": ["*://*.google.com/*"]
    },
    "permissions": [
        "activeTab",
        "tabs",
        "notifications",
        "storage"
    ],
    "web_accessible_resources": [{
        "matches": [
            "<all_urls>"
        ],
        "resources": [
            "**/*",
            "*"
        ],
        "use_dynamic_url": true
    }]
}


popup.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>hello world</h1>
</body>
</html>


download runable code sample

tzcvj98z

tzcvj98z1#

拥有“activeTab”权限并不意味着扩展自动接收当前活动选项卡的临时主机权限。
用户还必须通过执行以下操作之一来调用扩展:https://developer.chrome.com/docs/extensions/mv3/manifest/activeTab/#invoking-activeTab

  • 执行动作
  • 执行上下文菜单项
  • 从命令API执行键盘快捷键
  • 接受来自omnibox API的建议

https://developer.chrome.com/docs/extensions/mv3/manifest/activeTab/
当用户调用扩展(例如通过单击其操作)时,activeTab权限使扩展可以临时访问当前活动的选项卡。当用户在该页面上时,对选项卡的访问将持续,当用户导航离开或关闭选项卡时,对选项卡的访问将被撤销。
https://developer.chrome.com/docs/extensions/reference/tabs/#perms
“activeTab”权限
activeTab为当前选项卡赠款扩展临时主机权限以响应用户调用。与主机权限不同,activeTab不会触发任何警告。

相关问题