Chrome扩展名在当前textarea中替换单词 [英] Chrome Extension Replace word in current textarea

查看:161
本文介绍了Chrome扩展名在当前textarea中替换单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图制作一个chrome扩展程序,用于替换当前< textarea> 中键入的最后一个单词,当用户创建特定的 keydown 事件发生。所以我试过这个,但它并不真正起作用。



以下是我的扩展程序的文件:我的扩展程序的 manifest.json

  {
name:Test,
description :test,
version:0.0.1,
permissions:[
activeTab
],
background: {
scripts:[background.js],
persistent:false
},
browser_action:{
default_title:替换测试

manifest_version:2
}



< background.js


  chrome.tabs.executeScript( null,{file:content_script.js}); 

及其 content_script.js



  document.onkeydown = replacePrevWord; 

// Azerty:Ctrl +²
// Qwerty:Ctrl +'
function KeyPress(e){
var evtobj = window.event?事件:e
if(evtobj.keyCode == 222&& evtobj.ctrlKey)
返回true;
}


函数getCaretPosition(ctrl){
var CaretPos = 0; // IE支持
if(document.selection){
ctrl.focus();
var Sel = document.selection.createRange();
Sel.moveStart('character',-ctrl.value.length);
CaretPos = Sel.text.length;
}
// Firefox支持
else if(ctrl.selectionStart || ctrl.selectionStart =='0')
CaretPos = ctrl.selectionStart;
return(CaretPos);



函数returnWord(text,caretPos){
var index = text.indexOf(caretPos);
var preText = text.substring(0,caretPos);
if(preText.indexOf()> 0){
var words = preText.split();
return words [words.length - 1]; //返回最后一个单词
}
else {
return preText;



$ b函数replacePrevWord(){
if(KeyPress()){
var text = document.activeElement;
var caretPos = getCaretPosition(text)
var word = returnWord(text.value,caretPos);
if(word!= null){
text.value = text.value.replace(word,replaced);





这对JSFiddle( http://jsfiddle.net/cyo646cr/3/ ),但我不知道如何在Chrome扩展程序中做到这一点。



有什么想法?



谢谢。 / b>

解决方案

问题



您没有正确注入脚本。这很容易说,因为调用这个简单的行

  chrome.tabs.executeScript(null,{file:content_script.js }); 

会导致您的 background.js 仅在一次和当前选项卡中注入脚本(因为没有指定tabId)。因此,您的脚本只会在您打开的第一个标签中的每个Google Chrome浏览器会话中只运行一次 查看 chrome.tabs.executeScript 的文档


$ b

解决此问题



我有两个选择:
$ b


  1. 声明content_scripts字段在您的 manifest.json 中,因此它将被注入任何匹配模式的页面。
  2. 使用<$ c添加一个监听器$ c> chrome.tabs.onUpdated.addListener 方法,并在选项卡中注入脚本。 1

    manifest.json content_scripts字段$ c $>

      ... 
    content_scripts:[
    {
    匹配:[< al l_urls>],
    js:[content_script.js],
    run_at:document_idle,
    all_frames:true
    }
    ],
    ...

    现在您的内容脚本将被注入到每个页面因为< all_urls>将与所有页面匹配)以及页面的所有帧中。您可以找到有关content_scripts



    选项2



    请求 chrome.tabs API和您想在 manifest.json 中使用的网址:

      ... 
    权限:[
    activeTab,
    tabs,
    < all_urls>




    $ b $ 后台.js ,将一个监听器添加到 chrome.tabs.onUpdated 中,这将触发每个标签更新(即url更新),并插入脚本使用 chrome.tabs.executeScript ,如下所示:

      chrome.tabs .onUpdated.addListener(函数(tabID,info,tab){
    chrome.tabs.executeScript(tabID,{file:content_script.js});
    });

    请参阅 chrome.tabs.onUpdated 的文档。


    I'm trying to make a chrome extension that replaces the last word typed in the current <textarea> when the user makes a certain keydown event fire. So I've tried this but it doesn't really work.

    Here are the files of my extension:

    My extension's manifest.json:

    {
      "name": "Test",
      "description": "test",
      "version": "0.0.1",
      "permissions": [
        "activeTab"
      ],
      "background": {
        "scripts": ["background.js"],
        "persistent": false
      },
     "browser_action": {
        "default_title": "replace test"
      },
      "manifest_version": 2
    }
    

    Its background.js:

    chrome.tabs.executeScript(null, {file: "content_script.js"});
    

    And its content_script.js:

        document.onkeydown = replacePrevWord;  
    
    // Azerty: Ctrl + ² 
    // Qwerty: Ctrl + '
    function KeyPress(e) {
        var evtobj = window.event? event : e
        if (evtobj.keyCode == 222 && evtobj.ctrlKey)
            return true;
    }
    
    
    function getCaretPosition(ctrl) {
        var CaretPos = 0;   // IE Support
        if (document.selection) {
            ctrl.focus();
            var Sel = document.selection.createRange();
            Sel.moveStart('character', -ctrl.value.length);
            CaretPos = Sel.text.length;
        }
        // Firefox support
        else if (ctrl.selectionStart || ctrl.selectionStart == '0')
            CaretPos = ctrl.selectionStart;
            return (CaretPos);
    }
    
    
    function returnWord(text, caretPos) {
        var index = text.indexOf(caretPos);
        var preText = text.substring(0, caretPos);
        if (preText.indexOf(" ") > 0) {
            var words = preText.split(" ");
            return words[words.length - 1]; //return last word
        }
        else {
            return preText;
        }
    }
    
    
    function replacePrevWord() {
        if(KeyPress()){
            var text = document.activeElement;
            var caretPos = getCaretPosition(text)
            var word = returnWord(text.value, caretPos);
            if (word != null) {
                text.value =  text.value.replace(word,"replaced");
            }
        }
    }
    

    This works fine on JSFiddle (http://jsfiddle.net/cyo646cr/3/), but I don't know how to do this in a Chrome extension.

    Any ideas?

    Thanks.

    解决方案

    Issue

    You are not injecting the script correctly. It's easy to say, because calling this simple line

    chrome.tabs.executeScript(null, {file: "content_script.js"});
    

    in your background.js will result in injecting the script only one time and in the current tab (because no tabId is specified). Therefore your script will run only once for every session of Google Chrome in the first tab you open.

    Take a look at the documentation for chrome.tabs.executeScript.

    Work around

    To work around this problem you've got two options:

    1. Declare the "content_scripts" field in your manifest.json so it will be injected in any page that matches a pattern.
    2. Add a listener with the chrome.tabs.onUpdated.addListener method and inject the script on the tab.

    Option 1

    Declare the "content_scripts" field in your manifest.json like this:

    ...
    "content_scripts": [
        {
            "matches": ["<all_urls>"],
            "js": ["content_script.js"],
            "run_at": "document_idle",
            "all_frames": true
        }
    ],
    ...
    

    Now your content script will be injected in every page (because "<all_urls>" will match all the pages) and in all the frames of the pages. You can find helpful informations about the "content_scripts" here.

    Option 2

    Request the permissions for the chrome.tabs API and the URLs you want in your manifest.json:

    ...
    "permissions": [
        "activeTab",
        "tabs",
        "<all_urls>"
    ]
    ...
    

    In your background.js, add a listener to chrome.tabs.onUpdated, which will fire on every tab update (i.e. url update), and inject your script using chrome.tabs.executeScript, like this:

    chrome.tabs.onUpdated.addListener(function(tabID, info, tab) {
        chrome.tabs.executeScript(tabID, {file: "content_script.js"});
    });
    

    See the documentation for chrome.tabs.onUpdated.

    这篇关于Chrome扩展名在当前textarea中替换单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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