Reputation: 347
I want to bring the tab the extension is running on to the front of my window as soon as the match is found, even if I am currently working in a second window.
So far I have this code in my content_script.js, but it doesn't seem to work. The commented lines were my last failed tries.
The alert gave me -1, which seems to be quite the weird tab id.
if(output == 'found') {
sendResponse({findresult: "yes"});
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
//chrome.tabs.update(sender.tab.id, {selected: true});
//chrome.tabs.update(sender.tab.id, {active: true});
alert(sender.tab.id);
});
}
I've tried some things in the background.html too and all kinds of things already posted here, all with no luck.
What do I need to do to make this work?
EDIT
manifest.json script inclusion
"background": {
"scripts": ["background.js"]
},
"content_scripts": [ {
"all_frames": false,
"js": [ "jquery.js", "content_script.js" ],
"matches": [ "http://*/*", "https://*/*" ],
"run_at": "document_idle"
}
background.js (the alert won't even show up)
alert("here");
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
your_tab_Id = sender.tab.id);
});
chrome.tabs.update(your_tab_Id,{"active":true,"highlighted":true},function (tab){
console.log("Completed updating tab .." + JSON.stringify(tab));
});
content_script.js jQuery change background (sendResponse works, but if I activate the background changing line the script stops working)
if(found === true) {
//$('td:contains('+foundItem+')').css("background", "greenyellow");
sendResponse({findresult: "yes"});
}
jsFiddle I tested the jQuery code in
EDIT 2 extension download
Upvotes: 2
Views: 3646
Reputation: 18544
You can not use chrome.tabs API() from content script
To get tab id put your code to background.js
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
your_tab_Id = sender.tab.id);
});
and add this to background.js
page
chrome.tabs.update(your_tab_Id,{"active":true,"highlighted":true},function (tab){
console.log("Completed updating tab .." + JSON.stringify(tab));
});
Use only content script to send messages
chrome.extension.sendMessage("Awesome message");
Edit 1:
Your code do not work because of syntax error
Some point to consider:
sendMessage
in content script as well ( sendRequest is deprecated in favour of sendMessage)After applying above changes your code turns as shown here.
alert("here");
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
your_tab_Id = sender.tab.id;
chrome.tabs.update(your_tab_Id,{"active":true,"highlighted":true},function (tab){
console.log("Completed updating tab .." + JSON.stringify(tab));
});
});
Let me know if you need more information.
Upvotes: 2