【发布时间】:2019-12-12 03:18:15
【问题描述】:
当用户点击我的 chrome 扩展的 popup.html 中的按钮时,它会打开 form.html,其中有一个文本区域,用户可以在其中输入文本。用户在文本区域输入文本后,我希望 background.js 访问输入的文本。当用户切换选项卡时,我希望 background.js 抓取文本区域中的内容,即使 form.html 不是活动选项卡。
我已通过单击按钮将 document.getElementById("textarea").value 作为消息传递给 background.js,但我希望 background.js 在 form.html 不是活动选项卡时获取此值(并消除按钮)。
popup.html
<!DOCTYPE html>
<html style=''>
<head>
<head><title>activity</title></head>
</head>
<body style="width:600px;">
<div id="myText"></div><p>
<button type="button" class="button" id="btn1">Input info</button>
<script src="popup.js"></script>
</body>
</html>
popup.js
function onWindowLoad(callback) {
chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
var url = tabs[0].url;
document.getElementById("myText").innerHTML = url;
});
}
var button = document.getElementById("btn1");
button.addEventListener("click", function(){
chrome.tabs.create({url:"/form.html"});
});
window.onload = onWindowLoad();
form.html
<style>
html, body {
}
#myForm {
width: 100%;
height: 100%;
margin: auto;
position: relative;
padding: 0; }
</style>
<body>
<div class="form-popup" id="myForm">
<form id="s3paths" class="form-container">
<h2>Enter info here</h2><p>
<textarea rows="5" cols="80" id="textarea" placeholder = "example of what to input">
</textarea></p>
<button type="button" class="button" id="btn2">Load</button>
<script src="form.js"></script>
</form>
</div>
</body>
form.js
var button = document.getElementById("btn2");
button.addEventListener("click", function(){
alert('loaded!');
var port = chrome.runtime.connect({name: "paths"});
var spaths = document.getElementById("textarea").value;
port.postMessage({paths: spaths});
});
background.js
chrome.runtime.onConnect.addListener(function(port) {
port.onMessage.addListener(function(msg) {
alert(msg.paths);
});
});
如何让 background.js 从用户切换到的任何选项卡访问 document.getElementById("textarea").value of form.html?
【问题讨论】:
-
form.html需要在选项卡中打开。另外我认为后台不能直接访问它,需要一些消息传递。 -
弹出窗口仅在显示时运行,所以当它关闭时,所有内容都会立即丢失 - 您应该在 form.js 中的
'input'事件的侦听器中发送文本。
标签: javascript google-chrome-extension