Chrome扩展程序-无法识别JS功能 [英] Chrome extension - JS function is unrecognizable

查看:318
本文介绍了Chrome扩展程序-无法识别JS功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是chrome扩展程序开发的新手. 我正在尝试构建一个非常基本的扩展,只是为了查看其工作原理.

I'm new to chrome extensions development. I'm trying to build a very basic extension just to see how things work.

我要构建的扩展程序需要在网页中添加一个按钮以及所有"h1"元素.

The extension I want to build needs to add a button along with all "h1" elements in a web page.

这是我的js文件:

function myFunction(element) {
    alert(element.innerText);
};


var elements = document.querySelectorAll("h1");

for (var i = 0; i < elements.length; i++)
{
    var element = elements[i];
   // element.innerHTML += "<form><button type='button' value='Copy' onclick='myfunction(element)'></form>";
    element.innerHTML += "<button onclick='myFunction()'>Click me</button>";
};

当我单击按钮时,什么都没有发生, 似乎无法识别"myFunction".

When I click the button nothing happens, it seems that "myFunction" is not recognized.

这是我的清单:

{
  "manifest_version": 2,

  "name": "MagiCopy",
  "description": "This extension shows a Google Image search result for the current page",
  "version": "1.0",

  "browser_action":
  {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },

  "chrome_url_overrides":
  {
    "newtab" : "newtab.html"
  },

  "background":
  {
    "scripts": ["background.js"]
  },

  "permissions":
  [
    "activeTab",
    "https://ajax.googleapis.com/"
  ],

  "content_scripts":
  [
    {
      "matches": ["http://*/*", "https://*/*"],
      "js": ["myscript.js"],
      "run_at" : "document_end"
    }
  ]
}

我在做什么错了?

推荐答案

这里有很多问题,但让我们从最重要的问题开始.

There are many problems here, but let's start with the most important one.

Chrome扩展程序的内容脚本在隔离的环境中.

Chrome extensions have their content scripts live in an isolated environment.

内容脚本在称为隔离世界的特殊环境中执行.他们有权访问所注入页面的DOM,但不能访问该页面创建的任何JavaScript变量或函数.看起来每个内容脚本都好像在其上运行的页面上没有其他JavaScript在执行.反之亦然:页面上运行的JavaScript无法调用任何函数或访问由内容脚本定义的任何变量.

Content scripts execute in a special environment called an isolated world. They have access to the DOM of the page they are injected into, but not to any JavaScript variables or functions created by the page. It looks to each content script as if there is no other JavaScript executing on the page it is running on. The same is true in reverse: JavaScript running on the page cannot call any functions or access any variables defined by content scripts.

当您创建一个附加了内联代码的元素(onclick作为元素的参数)时,该代码将位于页面的上下文中.

When you create an element with an inline code attached to it (onclick as a parameter of the element), that code lives in the page's context.

由于上下文与内容脚本是隔离的,因此未在其中定义myFunction.

Since the context is isolated from your content script, myFunction is not defined in it.

此处正确的方法是完全避免使用内联脚本,并使用 addEventListener .

The correct way to do it here is to avoid inline scripting altogether and attach listeners using addEventListener.

也就是说,下一个问题:您正在操纵innerHTML来添加DOM.这是一个完全不好的主意,因为您可能会破坏状态信息.

That said, the next problem: you're manipulating innerHTML to add DOM. That's a thoroughly bad idea, as you're potentially destroying state information.

这是element.innerHTML += "something"的作用:

  1. element的内容转换为表示DOM节点的字符串.这样会丢弃之后附加到DOM节点的所有内容,例如事件侦听器.
  2. 在该字符串中添加内容".
  3. 丢弃element内部的所有DOM节点.
  4. element的内容替换为从结果字符串生成的DOM.
  1. Convert element's contents into a string representing the DOM nodes. This discards anything that was attached to DOM nodes afterwards - like event listeners.
  2. Add "something" to that string.
  3. Discard all DOM nodes inside element.
  4. Replace element's contents with DOM generated from the result string.

请勿潜在地破坏他人(或您自己)的作品.使用不会转换为字符串的适当DOM操作:创建一个节点,然后将其插入(附加)到所需的节点上.

Do not potentially destroy someone else's (or your own) work. Use proper DOM manipulation that doesn't go through conversion to string: create a node, and insert (append) it to the node you want.

var button = document.createElement("button");
button.text = "Click me";
button.addEventListener("click", myFunction);
element.appendChild(button);


最后,由于某些原因,您希望将element传递给myFunction.事件侦听器确实接收到一个参数,但它是Event对象.您可以使用其target属性,或者,如果我没有记错的话,甚至可以在监听器中使用this:


Finally, you expect for some reason that element will be passed to myFunction. Event listeners indeed receive an argument, but instead it's the Event object. You can use its target attribute, or, if I remember correctly, even this inside the listener:

function myFunction(e) { // e is the event
  console.log(e.target);
  console.log(this);
}

这篇关于Chrome扩展程序-无法识别JS功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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