首页 > 解决方案 > 从内容脚本注入表单提交数据(chrome 扩展)

问题描述

处理从内容脚本到后台脚本的数据传递有几个问题:

如何将数组从 background.js 传递到 inject.js(内容)脚本(Chrome 扩展)

从扩展背景或弹出到内容脚本的 sendMessage 不起作用

但是,据我所知,表单处理程序没有答案。举个例子:

清单.json:

{
  "manifest_version": 2,
  "name": "chrome-extension-bar",
  "description": "Chrome Extension Bar",
  "version": "1.0",

  "browser_action": {
    "default_title": "Chrome Extension Bar",
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  
  "permissions": [
    "<all_urls>",
    "tabs"
  ],

  "content_security_policy": "script-src 'self' https://ajax.googleapis.com/ https://maxcdn.bootstrapcdn.com ; object-src 'self'"
}

popup.html:

<html>
    <head>        
        <script type="application/javascript" charset="utf-8" src="popup.js"></script>
    </head>

    <body class="body-popup">
         // nothing needed here
    </body>
</html>

popup.js:

chrome.tabs.executeScript({
     file: "add-extension-content-script.js"
}, function() {
     console.log("Added extension!");
})

添加扩展内容脚本.js:

var form_element = htmlToElement(
    `
        <div>
            <label for="fname">First name:</label><br>
            <input type="text" id="fname" name="fname" value="John"><br>
            <button id="idSendButton" type="button" class="btn btn-secondary">Send</button>
        </form> 
    `
);

var current_title_bar = document.getElementById("global-nav");
current_title_bar.appendChild(form_element);

document.getElementById("idSendButton").addEventListener('click', function () {
    chrome.runtime.sendMessage({"name" : document.getElementById("fname").value}, function(response) {
        console.log('Got response: ' + response.farewell);
      });

});

如何让表单向内容脚本发送消息?内容脚本在接收到表单输入后单击页面上的按钮。

标签: javascripthtmlgoogle-chromegoogle-chrome-extension

解决方案


推荐阅读