javascript - 如何从 chrome 扩展程序填写网页表单中的文本字段?

标签 javascript jquery html css google-chrome

到目前为止,我已经有了一个扩展程序,它列出了用户所在的网页和一个按钮。单击该按钮时,应在文本字段中填写“testing123”。

在我测试的网页上,表单有一个 ID 和名称“form”,文本字段有一个 ID 和名称“body”。

如果我能在填写此文本字段或一般文本字段时得到一些帮助,我将不胜感激。

这是我目前拥有的文件:

list .json


    {
      "name": "Extension Menu",
      "version": "1.0",
      "manifest_version": 2,
      "description": "My extension",
      "browser_action": {
        "default_icon": "icon.png",
        "default_menu": "Menu",
        "default_popup": "popup.html"
      },
      "icons": {
        "128": "icon.png"
      },
      "permissions": [
          "tabs", "http://*/*", "activeTab"
        ]
    }

popup.html

<p id="currentLink">Loading ...</p>
<hr />
<ul id="savedLinks"></ul>
<script type="text/javascript" src="popup.js"></script><br>
<button type="button" onclick="fill in text box with the word 'testing123'">Go!</button>

popup.js


    chrome.tabs.getSelected(null, function(tab) {
      // $("#body").val("testing123");
      // document.getElementById('body').value = 'testing123';
      document.getElementById('currentLink').innerHTML = tab.url;
    });

我试过使用:

  1. $("#body").val("testing123");

  2. document.getElementById('body').value = 'testing123';

但他们似乎并没有工作。

最佳答案

您不能直接从popup 访问网页。你应该使用 content scripts去做这个。 内容脚本在网页上下文中运行。

将此添加到您的 list 中:

"content_scripts": [
        {
            "matches": [
                "http://www.example.com/*"
            ],
            "js": [
                "jquery.js",
                "myscript.js"
            ]
        },

myscript.js :

$("#body").val("testing123");

document.getElementById('body').value = 'testing123';

关于javascript - 如何从 chrome 扩展程序填写网页表单中的文本字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25107229/

相关文章:

javascript - jQuery is() 或 has() 作用于多个元素

javascript - null 是 JavaScript 中的对象吗?

jquery - 元素不显示时如何重新初始化插件

javascript - jQuery 函数更改 html 元素上 "value"属性的值

html - td 标签内的表延伸 td 标签

JavaScript 函数和按钮

javascript - rails/JSON : How to use JSON for jquery UI autocomplete form

javascript - 条件模板

javascript - Ajax获取的页面无法使用input type = "file"标签?

javascript - 网页适合分辨率