onclick或内联脚本在扩展程序中不起作用 [英] onclick or inline script isn't working in extension

查看:98
本文介绍了onclick或内联脚本在扩展程序中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎是最简单的操作,但它不起作用.在普通的浏览器中,.html和.js文件可以完美运行,但是在Chrome/Firefox扩展程序中,onClick函数无法执行应有的功能.

This seems to be the easiest thing to do, but it's just not working. In a normal browser the .html and .js files works perfectly, but in the Chrome/Firefox extension the onClick function is not performing what it's supposed to do.

.js文件:

function hellYeah(text) {
  document.getElementById("text-holder").innerHTML = text;
}

.html文件:

<!doctype html>
<html>
  <head>
    <title>
      Getting Started Extension's Popup
    </title>
    <script src="popup.js"></script>
  </head>
  <body>
    <div id="text-holder">
      ha
    </div>
    <br />
    <a onClick=hellYeah("xxx")>
      hyhy
    </a>
  </body>
</html>

因此,基本上,一旦用户单击"hyhy","ha",应更改为"xxx".再说一遍-它在浏览器中完美运行,但在扩展程序中不起作用.你知道为什么吗?以防万一我还要在下面附加manifest.json.

So basically once the user clicks "hyhy", "ha" should change into "xxx". And again - it works perfectly in the browser but does not work in the extension. Do you know why? Just in case I'm attaching the manifest.json below as well.

manifest.json:

manifest.json:

{
  "name": "My First Extension",
  "version": "1.0",
  "manifest_version": 2,
  "description": "The first extension that I made.",
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "permissions": [
    "http://api.flickr.com/"
  ]
}

推荐答案

Chrome扩展程序不允许您使用内联JavaScript(文档).

Chrome Extensions don't allow you to have inline JavaScript (documentation).
The same goes for Firefox WebExtensions (documentation).

您将必须执行以下操作:

You are going to have to do something similar to this:

为链接分配一个ID(<a onClick=hellYeah("xxx")>变为<a id="link">),然后使用 addEventListener 绑定事件.将以下内容放入您的popup.js文件:

Assign an ID to the link (<a onClick=hellYeah("xxx")> becomes <a id="link">), and use addEventListener to bind the event. Put the following in your popup.js file:

document.addEventListener('DOMContentLoaded', function() {
    var link = document.getElementById('link');
    // onClick's logic below:
    link.addEventListener('click', function() {
        hellYeah('xxx');
    });
});

popup.js应该作为单独的脚本文件加载:

popup.js should be loaded as a separate script file:

<script src="popup.js"></script>

这篇关于onclick或内联脚本在扩展程序中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆