如何在启用扩展时具有内容脚本功能,而无需重新加载网页



我是Chrome扩展程序开发的新手。我遵循了一些教程并创建了一个扩展。我正在尝试的扩展是突出显示 HOVER 上的网络元素。我的问题是扩展仅在页面加载时有效。它不适用于已打开的活动选项卡。我想确保单击图标时扩展程序在已打开的活动选项卡中工作。

清单:

   
{
	"manifest_version": 2,
	"name": "Highlight Web Element",
	"description": "Extension for highlighting element in a web page",
	"version": "1.0",
	"content_scripts": [
		{
			"matches": ["http://*/*","https://*/*"],
			"css": ["core.css"],
			"js": ["contentscript.js"],
			"run_at": "document_end",
			"all_frames": false
		}
	],
	"background" : {
		"scripts" : ["background.js"]
	},
	"browser_action": {
		//"default_icon": "logo .png"
	},
	"permissions": ["tabs", "activeTab"]
}

背景.js

chrome.browserAction.onClicked.addListener(function(tab) {
   chrome.tabs.executeScript(null, {file: "testScript.js"});   
});
chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
	  console.log(sender);
    console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");
    if (request.greeting == "hello")
      sendResponse({farewell: request.greeting, "srcElementTagName" : request.srcElementTagName});
  });

内容脚本.js

// Unique ID for the className.
var MOUSE_VISITED_CLASSNAME = 'plugin_crx_mouse_visited';
// 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) {
  var srcElement = e.srcElement;
  if(prevDOM != srcElement) {
	//console.log(srcElement.tagName);
	chrome.runtime.sendMessage({greeting: "hello", "srcElementTagName" : srcElement.tagName}, function(response) {
		console.log(response.farewell + " : " + response.srcElementTagName);
	});
  }
  // Lets check if our underlying element is a DIV.
  //if (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 iteration.
	prevDOM = srcElement;
  //}
}, false);

核心.css

.plugin_crx_mouse_visited {
  background-color: #bcd5eb !important;
  outline: 1px solid #5166bb !important;
}

我尝试在testScript.js中调用以下代码。但没有成功。

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
	  console.log(sender);
    console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");
    if (request.greeting == "hello")
      sendResponse({farewell: request.greeting, "srcElementTagName" : request.srcElementTagName});
  });

我只是用下面的方法解决了它。谢谢马金的回复!!

{
        "name": "Invoke when Extension is Clicked",
        "version": "1.0",
        "manifest_version": 2,
        "browser_action": {
			"name": "Click to get URL"
        },
        "background":{
            "scripts":["background.js"]
        },
        "permissions":["tabs", "activeTab"] //Put All your URL here
 }

背景.js

chrome.browserAction.onClicked.addListener(function (tab) { //Fired when User Clicks ICON
    
        chrome.tabs.executeScript(tab.id, {
            "file": "contentscript.js"
        }, function () { // Execute your code
            console.log("Script Executed .. "); // Notification on Completion
        });
   
});

内容脚本.js

// Unique ID for the className.
var MOUSE_VISITED_CLASSNAME = 'plugin_crx_mouse_visited';
// 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) {
  var srcElement = e.srcElement;
  if(prevDOM != srcElement) {
	//console.log(srcElement.tagName);
	chrome.runtime.sendMessage({greeting: "hello", "srcElementTagName" : srcElement.tagName}, function(response) {
		console.log(response.farewell + " : " + response.srcElementTagName);
	});
  }
  // Lets check if our underlying element is a DIV.
  //if (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 iteration.
	prevDOM = srcElement;
  //}
}, false);

使用 chrome://extensions 启用扩展,当单击活动选项卡上的图标时,扩展被调用,我能够突出显示 webelement。