Chrome executeScript函数不工作

Chrome executeScript function not working

本文关键字:工作 函数 executeScript Chrome      更新时间:2023-09-26

所以我正在编写一个扩展,当用户单击pageAction图标时,我正在尝试执行一个脚本。当点击图标时,该方法会调用chrome.tables.executeScript(…)。问题是chrome.tabs.executeScript函数没有执行,我不知道为什么。我知道我正在进入它调用executeScript的代码,因为我在那里出现了一个警报。这是我的一些代码:

manifest.json

{
  "manifest_version": 2,
  "name": "name here",
  "description": "description here",
  "version": "0.1",
  "permissions": [
    "<all_urls>",
    "tabs"
  ],
  "icons": {
    "16" : "images/icon16.png",
    "48" : "images/icon48.png",
    "128": "images/icon128.png" 
  },
  "background": {
    "scripts": ["js/check.js"]
  },
  "page_action": {
    "default_icon": {
      "19": "images/icon19.png",
      "38": "images/icon38.png"
    },
    "default_title": "default title here"
  }
}

js/check.js

chrome.tabs.onUpdated.addListener(checkForValidUrl);
function checkForValidUrl(tabId, changeInfo, tab) {
  if (tab.url.indexOf('g') > -1) {
    chrome.pageAction.show(tabId);
  }
};
chrome.pageAction.onClicked.addListener(function(tab) {
  alert("hello world"); //this code is executed...
  //...this code is not 
  chrome.tabs.executeScript(tab.id, {file: "save.js"}, function() {
    if(chrome.runtime.lastError) {
      console.error(chrome.runtime.lastError.message);
    }
  });
});

js/save.js

alert("hello world");

正如我在代码中所说,我的pageActiononClick函数中的hello世界是有效的。executeScript方法没有。任何关于正在发生的事情的想法都会有所帮助。

在我的代码中处理了很多不同的东西之后,我找到了问题的解决方案。错误似乎在写{file: "save.js"}的行中。当它在查找save.js时,它显然是在顶部目录中查找,即我的manifest.json文件所在的目录,而不是在我的代码所在的目录中。我必须将代码更改为{file: "js/save.js"}才能找到我的save.js文件。

根据文档:

若要在页面中插入代码,您的扩展必须对页面具有跨源权限。它还必须能够使用chrome.tabs模块。您可以使用清单文件的permissions字段获得这两种权限。

因此,您需要该站点的权限,即权限字段中的http://example.com/