当用户单击我的chrome扩展程序的popup.html中的按钮时,它将打开form.html,其中包含一个文本区域,用户可以在其中输入文本。用户在textarea中输入文本后,我希望background.js访问输入的文本。当用户切换标签时,即使form.html不是活动的标签,我也希望background.js能够捕获文本区域中的内容。
我已通过单击按钮将document.getElementById(“ textarea”)。value作为消息传递给background.js,但我希望当form.html不是活动选项卡时background.js可以获取此值(并消除按钮)。
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来访问form.html的document.getElementById(“ textarea”)。value?
答案 0 :(得分:1)
更新:我找到了解决方法。在将textarea中的值作为消息从form.js传递到background.js之后,我使用chrome.storage.sync进行存储,因此当我转到其他选项卡时,仍将其存储。 (我一直点击按钮)。
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) {
var paths = msg.paths;
chrome.storage.sync.set({key: paths}, function() {
//alert('Value is set to ' + paths);
});
});
});
当我希望使用存储的值时,在background.js中的其他位置:
chrome.storage.sync.get(['key'], function(result) {
if (!result.key){alert('Value is empty')}
else {alert(result.key);
//did stuff with result.key
};
})