Chrome扩展程序未收到来自content.js的响应

时间:2019-07-17 17:33:23

标签: javascript google-chrome-extension

基本上,我想要实现的是通过video接收视频参数content.js并将其发送到popup.jspopup.js发送问候,但无法(可能)收到来自content.js的响应

我关注了this tutorial,但id无效。有时它会漏掉这个错误

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

manifest.json

{
  "manifest_version": 2,
  "name": "UpCat",
  "version": "1.0.0",
  "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",
  "browser_action": {
    "default_popup": "popup.html",
    "default_title": "UpCat"
  },
  "permissions": [
          "tabs"
        ],
  "content_scripts":[
    {
      "matches":["https://www.youtube.com/watch?v=*"],
      "js":["content.js"]
    }
  ]

}

content.js

var getUrlParameter = function getUrlParameter(sParam) {
  var sPageURL = window.location.search.substring(1),
      sURLVariables = sPageURL.split('&'),
      sParameterName,
      i;

  for (i = 0; i < sURLVariables.length; i++) {
      sParameterName = sURLVariables[i].split('=');

      if (sParameterName[0] === sParam) {
          return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
      }
  }
};

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (request.greeting == "hello")
      var link = getUrlParameter('v');
      sendResponse({video: link});
});

popup.js

$(document).ready(function() {
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, workOn);
  });

  function workOn (res) {
    console.log(res.video);
  }
});

popup.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>It haz to works</title>
    <script src="jQuery/jquery-3.4.1.min.js"></script>
    <script src="jQuery/jquery-3.4.1.js"></script>
    <script src="popup.js"></script>
  </head>
  <body>
    <h1 class="inner">
      Hello there
    </h1>
  </body>
</html>

我希望收到popup.js的{​​{1}}响应,实际上是参数content.js,但它不会记录任何内容。

0 个答案:

没有答案