Chrome扩展程序:如何获取网页以访问由内容脚本定义的功能? [英] Chrome Extension: How do I get a web page to access functions defined by my content script?

查看:50
本文介绍了Chrome扩展程序:如何获取网页以访问由内容脚本定义的功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编程一个Chrome扩展程序,并让它注入一个内容脚本,该脚本会迭代几个元素,并向它们附加一个 onclick 属性,该属性会将消息发送到我的后台脚本,在DOM上执行自定义功能(内容脚本中定义的功能).要将消息从网页发送到扩展,我必须指定扩展ID,到目前为止,我是从扩展菜单中手动获取的.我是否可以查询扩展名自己的ID,以便注入与内容脚本对话的代码?还有另一种方法可以做我想做的事吗?

I'm programming a Chrome Extension, and I'm having it inject a content script which iterates through a few elements and attaches an onclick property to them which sends a message to my background script to execute a custom function on the DOM (the function defined in content scripts). To send a message from the web page to the extension, I must specify the extension ID which, as of now, I was manually getting from the extensions menu. Could I manage to query something for the extension's own ID so I can inject code that would talk to my content script? Is there another way to do what I'm trying to do?

为每个元素注入到DOM中的代码如下:

The code injected into the DOM for each of these elements looks like this

targets[current].element.setAttribute("onclick", `chrome.runtime.sendMessage(${EXTENSION_ID}, this.id)`);

推荐答案

有多种方法可以在您正在查看的特定选项卡和背景脚本之间交换信息.您可以在此答案中查看这些内容.

There are many ways to exhange information between the specific tab you're viewing and your background script. You can check those out on this answer.

您的Chrome扩展程序ID问题的解决方案是使用 chrome.runtime.id 获取扩展ID,并将其与您的其他代码一起注入所需的页面,然后使用它发送回消息.

The solution to your Chrome extension ID problem is using chrome.runtime.id to get the extension ID and inject it alongside your other code into the required page and then using it to send a message back.

这篇关于Chrome扩展程序:如何获取网页以访问由内容脚本定义的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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