executeScript 未定义或不是 ManifestV3 扩展中的函数 [英] executeScript is undefined or not a function in a ManifestV3 extension

查看:65
本文介绍了executeScript 未定义或不是 ManifestV3 扩展中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 Chrome 的这个功能不起作用?我正在尝试这个例子:https://developer.chrome.com/docs/extensions/mv3/content_scripts/#程序化.

Why is this function from Chrome not working? I'm trying this example: https://developer.chrome.com/docs/extensions/mv3/content_scripts/#programmatic.

我正在开发 chrome 扩展程序,并从 popup.js 向服务工作者 background.js 发送消息,并在 executeScript.

I'm developing an extension for chrome and sending a message from popup.js to service worker background.js and get error in executeScript.

chrome.runtime.sendMessage({ from: "newScript"}); 

manifest.json

{
    "manifest_version": 3,
    "name": "TennisBet",
    "version": "1.0",
    "description": "Extrension for bet on tennis.",
    "action": {
        "default_icon": {
            "256": "images/tennis256.png",
            "128": "images/tennis128.png",
            "64": "images/tennis64.png",
            "32": "images/tennis32.png",
            "24": "images/tennis24.png",
            "16": "images/tennis16.png"
        },
        "default_popup": "popup/popup.html"
    },
    "background": {
        "service_worker": "background-wrapper.js"
    },
    "host_permissions": ["*://*/*"],
    "permissions": [
        "tabs",
        "alarms",
        "activeTab",
        "declarativeContent",
        "storage"
    ]
}

background.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    switch(request.from){
        case "error":
            console.log(request.message);
            break;
        case "checkTabs":
            tabsWorker();      
            break;
        case "newScript":
            chrome.scripting.executeScript({ // Error in event handler: TypeError: Cannot read property 'executeScript' of undefined
                file: "content_scripts/cscript.js"
            });
            break;
        default:
            console.log("Message listener status active");
            break;
    }
});

推荐答案

ManifestV3 中的 executeScript 方法已经改变,现在在 chrome.scripting API 中:https://developer.chrome.com/docs/extensions/reference/scripting/

The executeScript method in ManifestV3 has changed and is now in chrome.scripting API: https://developer.chrome.com/docs/extensions/reference/scripting/

在 manifest.json 中添加这一行:

Add this line in manifest.json:

"permissions": ["scripting"] 

背景.js

chrome.scripting.executeScript({
    target: {tabId: id, allFrames: true},
    files: ['content_scripts/cscript.js'],
});

这篇关于executeScript 未定义或不是 ManifestV3 扩展中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆