【问题标题】:Add a button which calls a Content script function on click?添加一个在点击时调用内容脚本函数的按钮?
【发布时间】:2012-07-28 18:08:52
【问题描述】:

我在 Google Chrome 扩展的 content.js 中有以下代码:

jQuery(document).ready(function () {
    jQuery("body").html('<input type="button" id="soso" value="asd" onclick="goFrame()" />');
});
function goFrame() {
    alert('Value');
}

按钮创建成功,但是当我点击它时,消息没有出现,并且我在 Google Chrome 控制台中收到以下错误:

Uncaught ReferenceError: goFrame is not defined

【问题讨论】:

  • 您创建的 onclick 按钮指向页面上下文中的 goFrame。你的代码中的 goFrame 函数在内容脚本的上下文中,因为那是它被声明的地方。在JQuery("body")... 之后添加行document.querySelector('#sos').onclick=goFrame;
  • @PAEz jQuery 很容易学 ;) 绑定点击事件,使用.click() - api.jquery.com/click
  • @Rob W 我有一个令人震惊的记忆,所以喜欢只使用 JS,特别是因为我只使用 Chrome,所以有所有这些不错的新东西....让事情对我来说很简单 :)

标签: javascript jquery google-chrome google-chrome-extension content-script


【解决方案1】:

先读Chrome extension code vs Content scripts vs Injected scripts

解决问题,去掉内联事件监听,动态绑定事件:

    ...
    var $input = $('<input type="button" id="soso" value="asd">').click(goFrame);
    jQuery("body").html($input);
});
function goFrame() {
    alert('Value');
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多