I am sending a messages back and forth from background.js to the content script when a certain condition has been met String(historyItems.length) == "0"
. It works fine, but I noted that once the message has been sent once (not before that), the function displayMe();
at the other end is active, even when the when the condition has not been met.
background.js:
chrome.extension.onMessage.addListener(function (request, sender, sendResponse) {
chrome.history.search({
text: request.text,
maxResults: 10
}, function(historyItems) {
if(String(historyItems.length) == "0"){
chrome.tabs.query({currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
});
});
}
});
contentscript.js:
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.greeting == "hello"){
displayMe();
sendResponse({farewell: "goodbye"});
}
});
It is all triggered with this function in contentscript.js:
function buildUrlList(){
document.addEventListener('mouseover', function(event) {
var hoveredEl = event.target;
if (hoveredEl.tagName !== 'A') {
return;
}
chrome.runtime.sendMessage({text: "Trigger Search"});
});
}
I just want the function in the content script activate when the background.js send the message (once). How can I make this work (javascript only)?