在Chrome扩展程序和网页之间传递数据

时间:2018-12-19 16:43:37

标签: javascript google-chrome-extension dispatch

我正在尝试创建小的chrome扩展名。

此输入有一个包含登录名的输入,用户可以键入一个按钮。单击后,脚本将注入到当前页面,并且我正在尝试传递数据(在扩展名html中输入的登录名),但它似乎没有运行,并且我不知道如何对其进行更多测试以查找原因为什么它没有运行。

这时,alert(“ inject is running”);正在运行,但没有警报(“触发了csEvent”);当我按下按钮时,扩展管理器中没有错误消息。

代码如下:

清单

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime

time=['07:45','8:15','8:45','9:35','10:15','15:05','16:05']
truetime = [datetime.strptime(t, "%H:%M") for t in time]
value=[3,8,12,54,23,12,5]

plt.plot(truetime,value)
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter("%H:%M"))
plt.show()

buttonScript.js

{
"name" :"Quick Pass",
"version" :"1.0",
"manifest_version": 2,
"description" :"Password for quick access",
"browser_action" :
    {
        "default_icon" : "icone.png",
        "default_popup": "popup.html"
    },
    "web_accessible_resources": ["inject.js"],
    "permissions": [
    "https://*/*",
    "http://*/*",
    "tabs",
    "activeTab"
  ]
}

inject.js

document.getElementById("myButton").addEventListener("click", myFunction);

// When user clicks on the submit button of the extension, load the script on current tab
function myFunction() {
  chrome.tabs.getSelected(null, function(tab){
      chrome.tabs.executeScript({
          file: 'inject.js'
        });
    });

    // data you want to sent
    let data = {
        login: document.getElementById("loginPopup").value,
        pwd: "Password"
    };
    // send data through a DOM event
    document.dispatchEvent(new CustomEvent('csEvent', {detail: data}));

}

和popup.html:

// Injected from Chrome "APPI Pass" extension

(function() {

alert("inject is running");

document.addEventListener('csEvent', function (event) {

    alert("csEvent fired");
    console.log(event.detail.login+event.detail.pwd);

    document.getElementById("Email").value = event.detail.login;
    document.getElementById("Password").value = event.detail.pwd
    document.getElementByTagName("form").submit();
});

})();

谢谢

0 个答案:

没有答案