Chrome> 18:从扩展程序访问页面DOM

时间:2013-03-07 14:27:58

标签: javascript google-chrome dom google-chrome-extension

我正在进行第一次扩展。它必须分析被访问页面的HTML输入字段(不是我的,网上的任何一个),并最终改变那些字段的一些属性。

我的问题是,我如何访问和操作页面DOM?

我搜索了很多,但我找到的解决方案仅适用于Chrome版本< 18(在内容安全策略之前)。我无法在页面DOM中注入所需的代码。

的manifest.json

{
  "manifest_version": 2,

  "name": "TEST",
  "description": "...",
  "version": "1.0",

  "browser_action": {
    "default_icon": "test.png",
    "default_popup": "test.html"
  },
  "content_scripts": [{
    "matches": ["<all_urls>"],
    "js": ["jquery-1.9.1.min.js", "myscript.js"],
    "run_at": "document_end"
    }],
  "permissions": [
    "<all_urls>",
    "tabs"
  ]
}

myscript.js

var mytest ={
sInputClass:'populate',
...
    init:function() {
      console.log('INIT function');
      var arrInputs = mytest.getElementsByClassName(document, 'input', mytest.sInputClass);
      var iInputs = arrInputs.length;
    },

    /**
 * getElementsByClassName function included here for portability.
 * Remove if you are already using one.
 * Written by Jonathan Snook, http://www.snook.ca/jonathan
 * Add-ons by Robert Nyman, http://www.robertnyman.com
 */
getElementsByClassName:function(oElm, strTagName, strClassName) {
    var arrElements = (strTagName == "*" && document.all)? document.all : oElm.getElementsByTagName(strTagName);
    var arrReturnElements = new Array();
    strClassName = strClassName.replace(/\-/g, "\\-");
    var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
    var oElement;
    for(var i=0; i<arrElements.length; i++){
        oElement = arrElements[i];      
        if(oRegExp.test(oElement.className)){
            arrReturnElements.push(oElement);
        }   
    }
    return (arrReturnElements)
},
...
}

document.addEventListener('DOMContentLoaded', function () {

mytest.init();

});

其中mytest.init()是我在加载通用Internet页面时要执行的例程。

page.html中

<!doctype html>
<html>
  <head>
    <title>Getting Started Extension's Popup</title>
    <style type="text/css">
      .structural {
        position:absolute;
        left:-9999px;
      }
    </style>

  <!--<script src="myscript.js"></script>-->
  </head>
  <body>
    <form action="/search/">
      <div>
        <label for="searchtext" class="structural">Enter search text</label>
        <input type="text" name="searchtext" id="searchtext" title="Enter search text" class="populate">
      </div>
    </form>
    <form action="page.html">
      <input type="submit" value="Search">
    </form>
  </body>
</html>

mytest.init函数只有在我取消注释head脚本标签时才会执行,但我想为我要访问的每个页面执行脚本。

0 个答案:

没有答案