【问题标题】:pass data from popup to injected script将数据从弹出窗口传递到注入脚本
【发布时间】:2015-10-16 11:11:11
【问题描述】:

我正在开发一个 chrome 扩展,在此我使用内容脚本将 injection.js 注入网页。在injected.js中我有一个按钮,当我们点击这个按钮时,我会打开一个带有内部html文件的弹出窗口(window.open),现在我想将数据从弹出窗口发送到注入脚本

popup.html

<html>
  <head>

  </head>
  <body>
        <input id="mybutton" type="button" value="click" />
  </body>
  <script type="text/javascript" src="popup.js">

  </script>
</html>

popup.js

window.onload = function(){
var button = document.getElementById('mybutton');
button.onclick = function() {
  showAlert();
};
};

function showAlert(){
var evt=document.createEvent("CustomEvent");
evt.initCustomEvent("yourCustomEvent", true, true, "Data");
document.dispatchEvent(evt);
}

injected.js

$('.aic').append('<div id="sendButtonID" class="sendButtonCls" role="button" tabindex="0" gh="cm" style="-webkit-user-select: none;">Send Now</div></div>');
$('#sendButtonID').click(function(){
window.open(popupURL, '', 'height=400,width=500');
  //console.log('chrome: ',chrome);
});

document.addEventListener('yourCustomEvent', function (e)
{
 console.log('2');

 console.log("received "+e);
});

【问题讨论】:

  • 在你的 popup.js 中创建自定义事件是没有意义的
  • 那么在这种情况下该怎么办..?
  • 你不需要inject.js 来追加元素和监听点击事件。只需为此使用内容脚本
  • 只需使用内容脚本附加按钮并监听点击事件。然后使用内容脚本和弹出窗口之间的消息传递进行通信
  • @BharathKumar,注入的页面脚本只需要访问网页的javascript 变量。你需要吗?

标签: google-chrome-extension


【解决方案1】:

如果你将数据从弹出脚本传递到注入,你可以像这样传递,首先你应该从弹出脚本传递到内容脚本,然后从内容脚本传递到注入脚本

【讨论】:

    猜你喜欢
    • 2017-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多