javascript 使用 page-mod (Firefox Addon) 将 onclick 事件添加到特定按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10106033/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 08:44:05  来源:igfitidea点击:

Add onclick event to specific button with page-mod (Firefox Addon)

javascriptfirefox-addonfirefox-addon-sdk

提问by Jumpei Ogawa

I'm trying to develop firefox addon with addon builder.

我正在尝试使用插件构建器开发 Firefox 插件。

I want to modify mail editor of a web-based mailer. (In following code, I'm trying with Yahoo! Japan's mail service.)

我想修改基于 Web 的邮件程序的邮件编辑器。(在以下代码中,我正在尝试使用 Yahoo! Japan 的邮件服务。)

I want to execute specific code when the user press Send button.

我想在用户按下发送按钮时执行特定的代码。

The addon code is:

插件代码是:

main.js

main.js

var self = require("self");
var pageMod = require("page-mod");


pageMod.PageMod({
    include: "*.mail.yahoo.co.jp",
    contentScriptWhen: 'end',
    contentScript: "document.getElementById('send_top').setAttribute('onclick', 'alert(\"blabla\")');"
});

The button in email editor page:

电子邮件编辑器页面中的按钮:

<input id="send_top" class="inputbutton" type="submit" title="Submit an email"
       value="Submit" name="action_msg_send" accesskey="9">

When the user "Submit" button, I want to show dialog.

当用户“提交”按钮时,我想显示对话框。

回答by therealjeffg

It looks like you're not adding the onclick handler properly in your content script. You might instead use code like this:

看起来您没有在内容脚本中正确添加 onclick 处理程序。您可以改为使用这样的代码:

document.querySelector('#send_top').onclick = function() { 
    alert('bla bla'); 
}

Here's a working example of this in the add-on builder:

这是附加构建器中的一个工作示例:

https://builder.addons.mozilla.org/addon/1048430/latest/

https://builder.addons.mozilla.org/addon/1048430/latest/

One downside to using the contentScript property to add your content script code is that it is difficult to debug. A couple of pointers to make this easier:

使用 contentScript 属性添加内容脚本代码的一个缺点是难以调试。一些提示可以使这更容易:

  • always use 'contentScriptFile', and write your code in a separate js file that is located in your add-on's data folder.

  • test your code using Firefox's 'Scratchpad' developer tool, which you can open by going to Tools -> Developer -> ScratchPad. To do this:

    • open the page you're modifying
    • open Scratchpad
    • paste your JS code into Scratchpad
    • go to Execute -> Run to run your code
  • 始终使用“contentScriptFile”,并将代码编写在位于加载项数据文件夹中的单独 js 文件中。

  • 使用 Firefox 的“Scratchpad”开发工具测试您的代码,您可以通过转到工具 -> 开发人员 -> ScratchPad 打开该工具。去做这个:

    • 打开你正在修改的页面
    • 打开便签本
    • 将您的 JS 代码粘贴到 Scratchpad 中
    • 去执行 -> 运行运行你的代码