引用this post,我试图使用executeScript或sendMessage将变量传递给我的content.js文件。使用Chrome开发工具,我看到它正在到达我的content.js文件,它还会运行我插入的测试警报,但是当它到达
时<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="modal1" class="loginbox-user-modal">
<div class="loginbox-user-modal-container">
<div class="loginbox">
<span class="icon-close">close</span>
Modal 1
</div>
</div>
</div>
<div id="modal2" class="loginbox-user-modal">
<div class="loginbox-user-modal-container">
<div class="loginbox">
<span class="icon-close">close</span>
Modal 1
</div>
</div>
</div>
<div class="modal1"><a href="#">modal1</a></div><!--changed the class name to modal1, similar to the modal window id name-->
<div class="modal2"><a href="#">modal2</a></div>
它完全跳过它。我不确定这里发生了什么?
popup.js
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
或popup.js使用sendMessage
function search() {
var name = document.getElementById('txtSearch').value;
chrome.tabs.executeScript({ file: "jquery.js" }, function () {
chrome.tabs.executeScript(null, {
code: 'var name = ' + name + ';'
}, function () {
chrome.tabs.executeScript({ file: 'content.js' });
});
});
}
document.getElementById('btnSearch').addEventListener('click', search);
content.js
function search() {
var name = document.getElementById('txtSearch').value;
chrome.tabs.executeScript({ file: "jquery.js" }, function () {
chrome.tabs.executeScript({ file: 'content.js' }, function () {
chrome.tabs.sendMessage({ name: name });
});
});
}
document.getElementById('btnSearch').addEventListener('click', search);
答案 0 :(得分:1)
引用我在SO上找到的不同答案(无法找到它),我错过了一个将标签ID传递给内容脚本的函数。
chrome.tabs.query({ active: true }, function (tabs) {
chrome.tabs.sendMessage(tabs[0].id, {'type': type, 'name': name });
});