Chrome扩展程序网页检查器

时间:2019-02-19 13:30:16

标签: google-chrome google-chrome-extension google-chrome-devtools

我想编写一个Chrome扩展程序,可以在其中标记网站上的功能并将其保存在表格中,为此,我想使用Chrome Web检查器。 不幸的是,我是这个领域的新手(chrome插件),因此我正在寻找帮助(链接,教程,相关工作等)以在自己的扩展程序中使用Web检查器。

此网站https://ieeexplore.ieee.org/document/1005630上的简单示例。 我的想法是标记例如发布日期,然后插件将整个div写入表中。

1 个答案:

答案 0 :(得分:0)

实际上,我找到了一个简单的解决方案。

样本 http://g.recordit.co/5CCFjXpe8J.gif

这只是我的工具中的一小部分,使其保持简单。 主要思想来自Google Chrome Extension: highlight the div that the mouse is hovering over

  • “ iframe”是注入的侧边栏
  • marker.js包含用于标记div的脚本

manifest.json

{
    "name": "Feature extractor",
      "version": "1.0",
      "description": "Feature extractor from website",
      "permissions": ["activeTab", "declarativeContent", "storage", "contextMenus", "<all_urls>", "tabs"],
      "browser_action": {},
      "web_accessible_resources": ["iframe.html","iframe.js"],
      "background": {
        "scripts": ["background.js"],
        "persistent": false
      },
      "content_scripts": [
            {
                "matches": [
                    "http://*/*",
                    "https://*/*"
                ],
                "css": [
                    "marker.css"
                ],
                "js": [
                    "js/jquery-1.8.3.min.js",
                    "marker.js"
                ]
            }
        ],
      "manifest_version": 2
    }

background.js

    'use strict';

chrome.runtime.onInstalled.addListener(function() {
  chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
    chrome.declarativeContent.onPageChanged.addRules([{
      conditions: [new chrome.declarativeContent.PageStateMatcher({
        pageUrl: {hostEquals: 'developer.chrome.com'},
      })],
      actions: [new chrome.declarativeContent.ShowPageAction()]
    }]);
  });
});

// sidebar
chrome.browserAction.onClicked.addListener(function(){
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
        chrome.tabs.sendMessage(tabs[0].id,"toggle");
    })
});


// message passing
chrome.runtime.onMessage.addListener(function(request, sender, callback) {
    console.log(request);
    callback({'request':request});
});


// context menu
var labels = ['author','date','abstract']
for(var label in labels) {
    console.log(labels[label])
    chrome.contextMenus.create({id: labels[label], "title": labels[label], "contexts":['all']});
}

chrome.contextMenus.onClicked.addListener(function(info, tab) {
    if (info.menuItemId == labels[0]) {
        chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
            chrome.tabs.sendMessage(tabs[0].id,labels[0]);
        })
    }
});

iframe.html

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="css/jquery.mobile-1.2.1.min.css" />
    <script src="js/jquery-1.8.3.min.js"></script>
    <script src="js/jquery.mobile-1.2.1.min.js"></script>
  <script src="iframe.js"></script>
  </head> 
  <body>
  <button id="send">
    send
  </button>
  <div id="responses">
  </div>
  </body>
</html>

我需要jQuery.fn ..脚本来标识所选的div Get unique selector of element in Jquery

iframe.js

// unique selector
jQuery.fn.extend({
    getPath: function () {
        var path, node = this;
        while (node.length) {
            var realNode = node[0], name = realNode.localName;
            if (!name) break;
            name = name.toLowerCase();

            var parent = node.parent();

            var sameTagSiblings = parent.children(name);
            if (sameTagSiblings.length > 1) { 
                var allSiblings = parent.children();
                var index = allSiblings.index(realNode) + 1;
                if (index > 1) {
                    name += ':nth-child(' + index + ')';
                }
            }

            path = name + (path ? '>' + path : '');
            node = parent;
        }

        return path;
    }
});

window.addEventListener('DOMContentLoaded', function () {
  var callback = function (data) {
    $("#responses").append("<div>" + data + "</div>");
  };

  var send = function () {
    chrome.runtime.sendMessage(Date(), callback);
  }

  chrome.runtime.onMessage.addListener(function(msg, data){
        if (msg.command == "append-author") {
            $("#responses").append("<div>" + msg.el + "</div>")
        }
    })
  document.getElementById('send').addEventListener('click', send);
});

Google Chrome Extension: highlight the div that the mouse is hovering over

marker.js

// Unique ID for the className.
var MOUSE_VISITED_CLASSNAME = 'crx_mouse_visited';
var MOUSE_MARKED_CLASSNAME = 'crx_mouse_marked';

// Previous dom, that we want to track, so we can remove the previous styling.
var prevDOM = null;

// Mouse listener for any move event on the current document.
document.addEventListener('mousemove', function (e) {
    let srcElement = e.srcElement;

    // Lets check if our underlying element is a IMG.
    if (prevDOM != srcElement && srcElement.nodeName == 'DIV' ) {


        // For NPE checking, we check safely. We need to remove the class name
        // Since we will be styling the new one after.
        if (prevDOM != null) {
            prevDOM.classList.remove(MOUSE_VISITED_CLASSNAME);
        }

        // Add a visited class name to the element. So we can style it.
        srcElement.classList.add(MOUSE_VISITED_CLASSNAME);

        // The current element is now the previous. So we can remove the class
        // during the next ieration.
        prevDOM = srcElement;
        // console.info(srcElement.currentSrc);
        // console.dir(srcElement);
    }
}, false);

var iframe = document.createElement('iframe'); 
iframe.style.background = "green";
iframe.id = "comm-test-container";
iframe.style.height = "100%";
iframe.style.width = "0px";
iframe.style.position = "fixed";
iframe.style.top = "0px";
iframe.style.right = "0px";
iframe.style.zIndex = "9000000000000000000";
iframe.frameBorder = "none"; 
iframe.src = chrome.extension.getURL("iframe.html")

document.body.appendChild(iframe);

function toggle(){
    if(iframe.style.width == "0px") {
        iframe.style.width="400px";
    } else {
        iframe.style.width="0px";
    }
}

chrome.runtime.onMessage.addListener(function(msg, sender){
    if(msg == "toggle"){
        toggle();
    }
    if(msg == "author") {
        prevDOM.classList.add(MOUSE_MARKED_CLASSNAME);
        chrome.runtime.sendMessage({command:"append-author",el:prevDOM.innerHTML,selector:$(prevDOM).getPath()}, function(response) {});
    }
})

// find unique selector
jQuery.fn.extend({
    getPath: function () {
        var path, node = this;
        while (node.length) {
            var realNode = node[0], name = realNode.localName;
            if (!name) break;
            name = name.toLowerCase();

            var parent = node.parent();

            var sameTagSiblings = parent.children(name);
            if (sameTagSiblings.length > 1) { 
                var allSiblings = parent.children();
                var index = allSiblings.index(realNode) + 1;
                if (index > 1) {
                    name += ':nth-child(' + index + ')';
                }
            }

            path = name + (path ? '>' + path : '');
            node = parent;
        }

        return path;
    }
});

marker.css

.crx_mouse_visited {
    background-clip: #bcd5eb!important;
    outline: 1px dashed #e9af6e!important;
    z-index : 0!important;
}

.crx_mouse_marked {
    background-clip: #bcd5eb!important;
    outline: 5px solid #e9af6e!important;
    z-index : 0!important;
}