默山 2021-09-05 20:20 采纳率: 0%
浏览 40

chrome插件 chrome.extension.getBackgroundPage();返回undifined

我的 manifest版本是 3
是照着掘金一个博客写的,但是现在popup里面始终在 win.mdata = response;这里报错如下

img

看起来像是chrome.extension.getBackgroundPage(); 没获取到。源码如下,万分感谢:

manifest:

{
  "name": "Getting Started Example",
  "description": "Build an Extension!",
  "version": "1.0",
  "manifest_version": 3,
  "background": {
    "service_worker": "background.js"
  },
  "permissions": [
    "storage",
    "activeTab",
    "scripting"
  ],
  "content_scripts": [
    {
      "matches": [
        "<all_urls>"
      ],
      "js": [
        "js/jquery-3.6.0.min.js",
        "js/content-script.js"
      ]
    }
  ],
  "action": {
    "default_popup": "popup.html",
    "default_icon": {
      "16": "/images/get_started16.png",
      "32": "/images/get_started32.png",
      "48": "/images/get_started48.png",
      "128": "/images/get_started128.png"
    }
  },
  "icons": {
    "16": "/images/get_started16.png",
    "32": "/images/get_started32.png",
    "48": "/images/get_started48.png",
    "128": "/images/get_started128.png"
  },
  "options_page": "options.html"
}

background.js:

var mdata = null;

popup.js

$(function () {
  $("#btnCopy").on('click', function () {
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
      // alert(tabs[0].title);
      chrome.tabs.sendMessage(tabs[0].id, { action: "copy" }, function (response) {
        // alert(response);
        var win = chrome.extension.getBackgroundPage();
        alert(win);
        win.mdata = response;
        console.log(response);
      });
    });
  });

  $("#btnPaste").on('click', function () {
    var win = chrome.extension.getBackgroundPage();
    if (win.mdata) {
      chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
        chrome.tabs.sendMessage(tabs[0].id, { action: "paste", data: win.mdata }, function (response) {
          console.log(response);
        });
      });
    }
  });
});
  • 写回答

1条回答 默认 最新

  • 崽崽的谷雨 2021-09-06 09:19
    关注

    打印一下这个看看chrome.extension

    评论

报告相同问题?

问题事件

  • 创建了问题 9月5日