简体   繁体   English

如何从Chrome扩展程序的后台js访问页面元素

[英]How to access a page element from a background js of chrome extension

I have a context menu in my chrome extension and now I need to capture a specific page elements when the user click on that menu. 我的chrome扩展程序中有一个上下文菜单,现在当用户单击该菜单时,我需要捕获特定的页面元素。 This is my manifest file: 这是我的清单文件:

{
  "manifest_version": 2,
  "name": "Capture",
  "description": "This extension is capturing all text elements in the page",
  "version": "0.1",
  "permissions": ["contextMenus"],
  "background": {
    "scripts": ["jquery-2.0.2.js", "background.js"]
  },
  "manifest_version": 2
}

background.js background.js

function captureTextBoxes(e) {
    var textboxes = $(':text') ; 
        //alert(textboxes.length);
        textboxes.each(function (i){
        //code here
    }
}

chrome.contextMenus.create({
    title: "Capture All text box Elements", 
    contexts:["page"], 
    onclick: captureTextBoxes,
});

This was capturing 0 text box elements always. 这总是捕获0个文本框元素。 So I checked the passed document by adding following line: 所以我通过添加以下行来检查传递的文档:

    alert(document.documentElement.innerHTML);

It returns this : 它返回这个:

    <head></head>
    <body style="">
        <script src="jquery-2.0.2.js"></script>
        <script src="background.js"></script>
    </body>

This is not my actual page, but a dynamic page created by the chrome itself. 这不是我的实际页面,而是由Chrome本身创建的动态页面。 Is there anyway to access the actual page content that were right clicked for the context menu? 无论如何,是否可以访问右键单击上下文菜单的实际页面内容? (From a background javaScript) (从后台的javaScript)

The contextMenus.onClicked event (which triggers the callback specified by onclick ( in persistent background pages only )) is only available to the background page and the background page has no direct access to any web-page's DOM. contextMenus.onClicked事件(触发由onclick指定的回调( 仅在持久性后台页面中 ))仅对后台页面可用,并且后台页面无法直接访问任何网页的DOM。

If you want to manipulate the web-page DOM, you have to: 如果要操纵网页DOM,则必须:

  1. Inject a content script into the web-page. 将内容脚本插入到网页中。
  2. Pass a message to that content script, so it can manipulate the DOM for you. 将消息传递到该内容脚本,以便它可以为您操纵DOM。

(There are plenty of resources here in SO explaining how to achieve both.) (SO中有很多资源说明了如何实现两者。)

Take, also, a look at this answer to a similar question 也请看一下类似问题的答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM