简体   繁体   English

搜索并突出显示Chrome扩展程序当前页面上的文字

[英]Searching and highlighting text on current page for a Chrome Extension

How should I connect my pages to search and highlight text on current tab? 如何连接我的页面以搜索并突出显示当前选项卡上的文本?

Currently I have: 目前我有:

  • manifest.json does defining content/backgr/event page do significant things,auto inject code etc? manifest.json 定义内容/背景/事件页面做重要的事情,自动注入代码等?
  • popup.html essentially a shell for the search input which is used by search.js popup.html 本质上是search.js使用的搜索输入的shell
  • search.js should this be in background/event/content/popup.html page? search.js 应该在background / event / content / popup.html页面吗?

What I still don't understand after reading: 阅读后我仍然不明白的是:

What is a content page vs. background/event page? 什么是内容页面与背景/活动页面?

I know one is constantly running vs injected, but that's as much as I got from the chrome extension manual, I still don't quite understand if the content script/page is seperate from the popup.html for example and what the difference between a script in the popup.html vs content page/script is. 我知道有一个是经常运行vs注入,但这和我从chrome扩展手册中得到的一样多,我仍然不太明白内容脚本/页面是否与popup.html分开,例如a之间的区别是什么popup.html与内容页面/脚本中的脚本是。

What I know: 我知道的:

I know how to search for text on a page, and replace it or change its style etc. using JS. 我知道如何在页面上搜索文本,并使用JS替换它或更改其样式等。

I need to read up on the messaging API for Chrome Extensions. 我需要阅读Chrome扩展程序的消息传递API。

I know I need to know how to use the messaging API, is it going to be required for page search and highlighting? 我知道我需要知道如何使用消息传递API,它是否需要页面搜索和突出显示?

Summary: 摘要:

I don't need a walk through or full answer, just a little help visualizing how Chrome extensions work, or at minimum how I should set mine up in relation to page interaction IE: 我不需要浏览或完整答案,只需一点帮助可视化Chrome扩展程序的工作方式,或者至少我应该如何设置与页面交互相关的IE:

search.js content page injected >>>>> popup.html search.js内容页面注入>>>>> popup.html

and maybe a short bit about how injection works in chrome extensions(IE, do I only need to specify that it is content page in manifest.json to have it injected or is there more work to it)/expected behavior? 也许还有一点关于注入如何在chrome扩展中起作用(IE,我只需要指定它是manifest.json中的内容页面,以便注入它还是有更多的工作)/预期的行为?

Apologies for the jumbled thoughts/question/possibly missing the things relevant to my questions while reading the manual. 在阅读手册时,为混乱的想法/问题/可能遗漏与我的问题相关的事情道歉。

I will start with making the purpose of each kind of page/script more clear. 我将首先使每种页面/脚本的目的更加清晰。


First is the background page/script . 首先是background page/script The background script is where your extension lives. background script是您的扩展程序所在的位置。 It isn't required, but in order to do most extension things, you need one. 这不是必需的,但为了做大多数扩展事情,你需要一个。 In it you can set up various event listeners and such depending on what you want it to do. 在其中,您可以设置各种事件侦听器,具体取决于您希望它做什么。 It lives in its own little world and can only interact with other pages and scripts using the chrome.* apis. 它存在于自己的小世界中,只能使用chrome.* apis与其他页面和脚本进行交互。 If you set it up as an event page it works exactly the same except that it unloads when not in use and loads back into memory when it has something to do. 如果将其设置为事件页面,则它的工作方式完全相同,只是在不使用时卸载并在有事情时将其加载回内存。

Content scripts refer to injected Javascript and/or css. Content scripts是指注入的Javascript和/或css。 They are the primary tool used for interacting with web pages. 它们是用于与网页交互的主要工具。 They have very limited access to chrome.* apis, but they have full access to the DOM of the page they are injected into. 他们对chrome.* apis的访问权限非常有限,但是他们可以完全访问他们注入的页面的DOM。 We will come back to using them in a minute. 我们将在一分钟后回来使用它们。

Now for Popup pages . 现在为Popup pages Unlike the background script and content script , popups have both a HTML and JS portion. background scriptcontent script ,弹出窗口同时包含HTMLJS部分。 The HTML part is just like any other page, just small and as a overlay popup coming out from the icon. HTML部分就像任何其他页面一样,只是很小,并且是从图标中显示的叠加弹出窗口。 The script portion of it, however, can do all the things the background page does, except that it unloads whenever the popup is closed. 但是,它的脚本部分可以完成后台页面所做的所有操作,只要它在弹出窗口关闭时卸载。


Now that the distinctions are more clear let's move on to what you want to do. 既然区别更加清晰,那就让我们继续你想要做的事情。 It sounds like you want to open the popup, have the user enter text to search for in the current tab, then highlight that text on the page. 听起来您想要打开弹出窗口,让用户在当前选项卡中输入要搜索的文本,然后在页面上突出显示该文本。 Since you said that you already know how you plan on highlighting the text, I will leave that part to you. 既然你说你已经知道如何突出显示文本,我将把这部分留给你。

First to set up our manifest file. 首先设置我们的清单文件。 For this particular action, we don't need a background script. 对于此特定操作,我们不需要后台脚本。 What we do need is both the "tabs" and "activeTab" permissions. 我们需要的是"tabs""activeTab"权限。 These will enable us to inject our script later. 这些将使我们以后能够注入我们的脚本。 We also need to define the browser action with it's popup. 我们还需要使用它的弹出窗口定义浏览器操作。 Altogether it would look something like this: 总而言之,它看起来像这样:

"browser_action": {
  "default_icon": "icon.png",
  "default_popup": "popup.html" 
},
"permissions": [
  "tabs", "activeTab"
]

Now in our popup.html file, we can only have markup and css, no inline code at all. 现在在我们的popup.html文件中,我们只能有标记和css,根本没有内联代码。 We will put it all in our js file and include it. 我们将把它全部放在我们的js文件中并包含它。 Something like this should work: 这样的事情应该有效:

<!DOCTYPE html> 
<html>
  <head>
    <script src="popup.js"></script>
  </head>
  <body>
    <input type="text" id="searchText">
    <button id="searchButton">Search</button>
  </body>
</html>

This is where we come back to the content script stuff. 这是我们回到内容脚本的地方。 There are two ways to inject a content script, first is to define it in the manifest. 注入内容脚本有两种方法,首先是在清单中定义它。 This works best when you always want to inject it for a particular set of url's. 当你总是想为一组特定的URL注入它时,这种方法效果最好。 Second, to use the chrome.tabs.executeScript method to inject it when we need to. 其次,使用chrome.tabs.executeScript方法在需要时注入它。 That is what we will use. 这就是我们将要使用的。

window.onload = function(){
  document.getElementById('searchButton').onclick = searchText;
};
function searchText(){
  var search = document.getElementById('searchText').value;
  if(search){
    chrome.tabs.query({active:true,currentWindow:true},function(tabs){
      chrome.tabs.executeScript(tabs[0].id,{file:search.js});
      chrome.tabs.sendMessage(tabs[0].id,{method:'search',searchText:search});
    });
  }
}

With this, we have successfully injected our script and then send the search text to that script. 有了这个,我们已经成功注入了我们的脚本,然后将搜索文本发送到该脚本。 Just make sure that the script is wrapped in a onMessage listener like this: 只需确保脚本包含在onMessage监听器中,如下所示:

chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){
  // message.searchText is the text that was captured in the popup    
  // Search/Highlight code goes here
});

And that pretty much sums it up. 这几乎总结了它。 With that, you should be able to get it working. 有了它,你应该能够让它工作。 If something is still not clear let me know and I will fix it. 如果仍然不清楚,请告诉我,我会解决它。

I think what's confusing you is the non-existant concept of a "content page". 我认为令人困惑的是“内容页面”的不存在概念。 There is no such thing. 哪有这回事。 What you're likely referring to is a "content script". 您可能指的是“内容脚本”。 Let me explain the three main components of an extension: 让我解释一下扩展的三个主要组成部分:

Background Page 背景页面

As you said, this is the persistent aspect of a Chrome Extension. 正如您所说,这是Chrome扩展程序的持久性方面。 Even though it can be HTML page it is never rendered. 即使它可以是HTML页面,它也永远不会被渲染。 You simply use it to run JavaScript and other content that stays persistent. 您只需使用它来运行JavaScript和其他保持持久性的内容。 The only way to "refresh" the background page is to refresh the extension in the extension manager, or to re-install the extension. “刷新”后台页面的唯一方法是刷新扩展管理器中的扩展,或重新安装扩展。

This is most useful for saving information that should remain persistent, such as authentication credentials, or counters that should build up over time. 这对于保存应保持持久性的信息(例如身份验证凭据或应随时间累积的计数器)非常有用。 Only use the background page when absolutely necessary, though, because it consumes resources as long as the user is running your extension. 但是,只有在绝对必要时才使用后台页面,因为只要用户运行您的扩展,它就会消耗资源。

You can add a background script like to manafest file like this: 您可以添加像manafest文件这样的后台脚本,如下所示:

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

Or like this: 或者像这样:

"background": {
    "page": "background.html"
},

Then simply add background.js to background.html via a typical tag. 然后只需通过典型标记将background.js添加到background.html。

Popup 弹出

This is what you see when you click the icon on the toolbar. 这是您单击工具栏上的图标时看到的内容。 It's simply a popup window with some HTML. 它只是一个带有一些HTML的弹出窗口。 It can contain HTML, JavaScript, CSS, and whatever you would put in a normal web page. 它可以包含HTML,JavaScript,CSS以及您在普通网页中放置的任何内容。

Not all extension need a popup window, but many do. 并非所有扩展都需要弹出窗口,但很多都可以。 For example, your highlight extension may not need a popup if all it's doing is highlighting text on a page. 例如,如果您所做的一切都突出显示页面上的文本,则您的突出显示扩展可能不需要弹出窗口。 However, if you need to collect a search result (which seems likely) or provide the user with some settings or other UI then a popup is a good way to go about this. 但是,如果您需要收集搜索结果(似乎很可能)或为用户提供某些设置或其他UI,那么弹出窗口是一个很好的方法。

You can add a popup to the manifest file like this: 您可以像这样在清单文件中添加一个弹出窗口:

"browser_action": {
    "default_popup": "popup.html"
},

Content script 内容脚本

As I mentioned, this is not a "page" per se -- it a script, or set of scripts. 正如我所提到的,这不是一个“页面”本身 - 它是一个脚本或一组脚本。 A content script is what you use to infuse JavaScript into pages the user is browser. 内容脚本是用于将JavaScript注入用户浏览器页面的内容。 For example, a user goes to Facebook and a content script could change the background to red. 例如,用户访问Facebook并且内容脚本可以将背景更改为红色。 This is almost certainly what you'll need to use to highlight text on a page. 几乎可以肯定,您需要使用它来突出显示页面上的文本。 Simply infuse some JavaScript and any necessarily libraries to search the page or crawl the dom, and render changes to that page. 只需注入一些JavaScript和任何必需的库来搜索页面或抓取dom,并呈现对该页面的更改。

You can inject content scripts every time a user opens any URL like this: 每次用户打开任何URL时,您都可以注入内容脚本:

"content_scripts": [
    {
        "matches" : [
            "<all_urls>"
        ],
        "js" : [
            "content.js"
        ]
    }
],

The above injects "content.js" into "all urls". 以上将“content.js”注入“所有网址”。

You'll also need to add this to the permissions: 您还需要将此添加到权限:

"permissions": [
    "<all_urls>",
]

You can even add JQuery to the list of content scripts. 您甚至可以将JQuery添加到内容脚本列表中。 The nice thing about extensions is that the content scripts are sandboxed, so the version of JQuery you inject will not collide with JQuery on pages the user visits. 扩展的好处是内容脚本是沙盒的,因此您注入的JQuery版本不会在用户访问的页面上与JQuery发生冲突。

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

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