首页 > 解决方案 > 为什么编译后内容脚本不加载?

问题描述

我正在编写一个 Chrome 扩展程序,它从队列中获取 URL,在新窗口中打开它,运行内容脚本,然后重复。为了便于开发,我已经开始将其迁移到 Webpack 和 Typescript 的任务,但是我遇到了在所有内容都被转译后内容脚本未加载的问题。

此扩展在不通过 webpack 和 typescript 运行时可以正常工作。一旦我将预先存在的代码与样板集成在一起,除了内容脚本之外的所有内容都可以正常工作。

src/content_script.ts

import extactor from './scripts/extractor';

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  if (request.extractData) {
    console.log("received data extraction request", request);
    extactor().then(data => {
      sendResponse(data);
    });
    return true;
  }
});

webpack/webpack.common.js

  context: path.join(__dirname, "../"),
  entry: {
    popup: path.join(__dirname, srcDir + "popup.ts"),
    background_script: path.join(__dirname, srcDir + "background_script.ts"),
    content_script: path.join(__dirname, srcDir + "content_script.ts")
  },
  output: {
    path: path.join(__dirname, "../dist/js"),
    filename: "[name].js"
  },
  optimization: {
    splitChunks: {
      name: "vendor",
      chunks: "initial"
    }
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        loader: "ts-loader",
        options: {
          transpileOnly: true
        },
        exclude: /node_modules/
      }
    ]
  }
};

和 manifest.json

{
    "manifest_version": 2,
    "permissions": ["<all_urls>", "tabs", "notifications", "storage", "downloads"],
    "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",
    "background": {
        "scripts": [
            "js/background_script.js"
        ]
    },
    "content_scripts": [
        {
            "matches": ["*://*/*"],
            "js": [
                "js/content_script.js"
            ]
        }
    ]
}

在非 typescript/webpack 分支中,扩展工作正常,尝试运行转译代码将导致 popup.js 和后台脚本正常工作,但由于 content_script.js 未运行,后台页面返回

Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.

标签: typescriptwebpackgoogle-chrome-extension

解决方案


推荐阅读