我正在尝试通过在Chrome扩展程序中抓取特定的Gmail正文来将值保存到文本框。我能够在控制台中获取值,但无法在文本框中获取它们,每次打开弹出窗口时,控制台中都会出现错误Uncaught ReferenceError: $ is not defined
。这是我的密码,
popup.html
<head>
<title>Gmail Body Scrapper</title>
<script src="jquery-1.9.1.min.js"></script>
<script src="popup.js"></script>
<style>
body { width: 600px; height: 400px; }
input[type=text] { margin: 5px; }
</style>
</head>
<body>
<b>Email : </b><input type="text" id="email" /><br>
<b>Phone : </b><input type="text" id="phone" /><br>
<b>First Name : </b><input type="text" id="first" /><br>
<b>Last Name : </b><input type="text" id="last" /><br>
<button id="btnGet">Submit</button><br><br>
</body>
popup.js
$(document).ready(function () {
chrome.tabs.query({'active': true, 'windowId': chrome.windows.WINDOW_ID_CURRENT},
function(tabs) {
var getUrl = tabs[0].url;
var verifyUrl = getUrl.indexOf("mail.google.com");
if (verifyUrl >= 0) {
var verifyOpened = getUrl.indexOf("#inbox/");
if (verifyOpened < 0) { return 0; }
} else {
return 0;
}
function modifyDOM() {
var gBody = document.body.innerText;
var first = gBody.slice(gBody.indexOf(",f:")+3, gBody.indexOf(",l:")).trim();
var last = gBody.slice(gBody.indexOf(",l:")+3, gBody.indexOf(",t:")).trim();
var phone = gBody.slice(gBody.indexOf(",p:")+3, gBody.indexOf(",e:")).trim();
var email = gBody.slice(gBody.indexOf(",e:")+3, gBody.indexOf(",fn:")).trim();
var arr = [first, last, phone, email];
console.log(arr);
$('#first').val(first); // Error starts from this line
$('#last').val(last);
$('#phone').val(phone);
$('#email').val(email);
}
chrome.tabs.executeScript({
code: '(' + modifyDOM + ')();' //argument here is a string but function.toString() returns function's code
}, (results) => {
console.log('Popup script:')
console.log(results[0]);
});
}
);
});
打开扩展弹出窗口时,如何在文本框中存储值?急需此帮助,谢谢!
答案 0 :(得分:1)
modifyDOM()在网页上下文(完全不同的文档)中运行,因此您只应返回结果,该结果将在弹出窗口的上下文中执行executeScript回调:
function modifyDOM() {
const gBody = document.body.innerText;
return {
first: gBody.match(/,f:([\s\S]*),l:|$/)[1].trim(),
last: gBody.match(/,l:([\s\S]*),t:|$/)[1].trim(),
phone: gBody.match(/,p:([\s\S]*),e:|$/)[1].trim(),
email: gBody.match(/,e:([\s\S]*),fn:|$/)[1].trim(),
};
}
chrome.tabs.executeScript({code: `(${modifyDOM})()`}, results => {
$.each(results[0], (id, text) => $('#' + id).val(text));
});
还请注意,由于弹出窗口是一个单独的窗口,因此它具有separate devtools and console。