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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25107229/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 03:57:33  来源:igfitidea点击:

How to fill out a textfield within a form on a webpage from a chrome extension?

javascriptjqueryhtmlcssgoogle-chrome

提问by ayaz15m

So far I have got an extension that lists out the webpage the user is on and a button. The button should, when clicked, fill in the textfield with "testing123".

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

On the webpage where I am testing the form has a id and name "form" and the textfield has an id and name "body".

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

If I could get some help filling in this textfield or a general textfield it would be greatly appreciated.

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

Here are the files I have so far:

以下是我目前拥有的文件:

manifest.json

清单文件.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

弹出窗口.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

弹出窗口.js

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

I have tried using:

我试过使用:

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

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

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

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

but they do not seem to be working.

但他们似乎没有工作。

采纳答案by Parag Gangil

You can't access the webpage directly from popup. You should use content scriptsto do this. Content scriptsrun in the context of the webpage.

您无法直接从 访问该网页popup。您应该使用内容脚本来执行此操作。Content scripts在网页的上下文中运行。

Add this to your manifest :

将此添加到您的清单中:

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

myscript.js:

我的脚本.js

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

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