Chrome扩展程序 - 无法使用Chorme * .API启动外部网站

时间:2017-05-16 12:38:00

标签: javascript google-chrome google-chrome-extension

我正在学习如何创建Chrome扩展程序。我刚开始开发一个用于启动亚马逊网站并在其上执行搜索活动。我使用过内容脚本。但是我的代码在第一次警报后没有工作。请在下面找到我的代码:

> manifest.json :清单文件

<!-- language: lang-json -->

    {
      "name": "TestChrome Extension",
      "version": "0.0.1",
      "manifest_version": 2,
       "background": {
        "scripts": ["popup.js"]
      },
      "permissions": [
        "tabs",
        "<all_urls>"
      ],

      "content_scripts": [
        {
          "matches": [
            "<all_urls>"
          ],
          "js": [ "contentscript.js" ]
          //"run_at": "document_end"
        }
      ],

      "browser_action": {
        //"default_popup": "popup.html",
        "default_icon": "icon.png",
        "default_title": "That's the tool tip of extension"
      }
    }

&GT; popup.js :我正在使用getElementbyId方法的弹出文件/后台脚本

<!-- language: lang-javascript -->

   // Called when the user clicks on the browser action.
chrome.browserAction.onClicked.addListener(function (tab) {
    // Send a message to the active tab
    alert("Clicked Recognised");
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
        var activeTab = tabs[0];
        console.log("URL from main.js", activeTab);
        chrome.tabs.sendMessage(activeTab.id, { "message": "clicked_browser_action" });
    });
});

chrome.runtime.onMessage.addListener(
  function (request, sender, sendResponse) {
      if (request.message === "open_new_tab") {
          chrome.tabs.create({ "url": request.url });
          document.getElementById("twotabsearchtextbox").textContent = "Iphone 7";
          document.getElementsByClassName("nav-input").addEventListener("click", function () {
              window.alert("You Clicked Me");
          });
     }
  }
);
chrome.tabs.executeScript(null, { file: "contentscript.js", allFrames: true });

&GT; contentscript.js :下面是我的内容脚本的代码

<!-- language: lang-javascript -->

    chrome.runtime.onMessage.addListener(
  function (request, sender, sendResponse) {
      if (request.message === "clicked_browser_action") {
          alert("CONTENT SCRIPT: I am running!");
         // var firstHref = $("a[href^='http']").eq(0).attr("href");
          var firstHref = "http://www.amazon.in";
          //console.log(firstHref);
          chrome.runtime.sendMessage({ "message": "open_new_tab", "url": firstHref });
      }
  }
);

我按照建议修改了我的脚本。请参阅上面的代码。

0 个答案:

没有答案