【问题标题】:Chrome Extension -> ExecuteScript: function call doesn' workChrome 扩展 -> ExecuteScript:函数调用不起作用
【发布时间】:2014-10-29 14:49:18
【问题描述】:

他是我的ma​​nifest.json

{
  "name": "Page Redder",
  "description": "Make the current page red",
  "version": "2.0",
  "permissions": [
    "activeTab","*://*/*"
  ],
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "browser_action": {
    "default_icon" : "icon.png",
    "default_title": "Make this page red"
  },
  "manifest_version": 2
}

这里是 background.js 有效(页面变为红色):

chrome.browserAction.onClicked.addListener(function(tab) {

   chrome.tabs.executeScript(null, {code:'document.body.style.backgroundColor="red";'} );


});

如果我按以下方式更改 background.js,它就无法工作:

function changeColor() {
    document.body.style.backgroundColor="red";

}

chrome.browserAction.onClicked.addListener(function(tab) {

   chrome.tabs.executeScript(null, {code:';'}, function() {
      changeColor();
   });

});

Chrome 版本:38.0.2125.111

问题:我在这里做错了什么?为什么在executeScript中调用函数不起作用?

谢谢, 浣熊

【问题讨论】:

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


    【解决方案1】:

    你没有调用函数in executeScript

    您在其回调中调用该函数,该函数在原始(后台)页面中运行。这是一个描述“executeScript 完成时要做什么”的函数,而不是要运行的代码。

    在您要注入代码的页面中实际运行的代码是“;” (显然什么也没做)。

    可以run a function defined in your codeexecuteScript 正确转换为字符串。但请注意,它无法访问函数外部定义的变量。


    我认为您要尝试做的是让代码接受一个参数(颜色)。您应该考虑使用Messaging 来传递命令,而不是每次都编写自定义代码。

    示例:添加文件content.js,内容如下:

    // Include guard: only execute once
    if (!injected) {
      injected = true;
      init();
    }
    
    function init() {
      // Get ready to receive a command
      chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
        if(message.action == "colorBackground") {
          document.body.style.backgroundColor = message.color;
        }
      });
    }
    

    在你的后台,你可以这样做:

    chrome.tabs.executeScript(null, {file: "content.js"}, function() {
      // File executed, it's ready for the message
      chrome.tabs.sendMessage(null, { action: "backgroundColor", color: "green" });
    }
    

    【讨论】:

    • Xan,感谢您的宝贵回答!不,我不尝试接受参数。这是使用我可以想象的函数的最简单示例。实际上,我想对表单字段进行一些操作,但不想将代码呈现为一个字符串。所以我想将代码放在函数中并从 executeScript 运行它。没有消息可以吗?谢谢,浣熊。
    • 有可能,见linked question。但这不是一个很好的架构。
    • 如果你想重复运行一些较长的代码,可以考虑把它放在一个js文件中并执行{file: "filename.js"}
    猜你喜欢
    • 1970-01-01
    • 2013-12-24
    • 2017-05-26
    • 2012-01-22
    • 2012-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多