I am developing a Chrome extension to add functionality to a site developed by other users. I do not control their code.
My code is intended only to work on certain pages of my site. Since the content is sensitive, I use the API chrome.declarativeContentto make sure that I do not generate any permission warnings when my extension is installed, which may hit my potential users.
I have a site author , sometimes uses jQuery to rewrite part of the content on the page using jQuery Mobile. This event changes the URL. The Chrome extension API does not respond to this change and leaves the icon pageAction, and the script content is active.
As a result, every time I return to a page that matches mine PageStateMatcher, Chrome adds another instance of my script content to the page. When the user clicks the icon pageAction, the script fires several times, creating unwanted results.
How can I remove icon pageActionand content script after changing jQuery content?
the code:
=== background.js ===
var match_rules = {
conditions: [
new chrome.declarativeContent.PageStateMatcher({
pageUrl: {
hostSuffix: '.example.com',
pathSuffix: '/reports/report.asp',
schemes: ['https']
}
})
],
actions: [ new chrome.declarativeContent.ShowPageAction() ]
};
chrome.runtime.onInstalled.addListener(function(details) {
chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
chrome.declarativeContent.onPageChanged.addRules([match_rules]);
});
});
chrome.pageAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(null, {file: 'content_script.js'}, function(result){
chrome.tabs.sendMessage(tab.id, {action: 'go'},
function(response){
console.log(response);
});
});
});
=== content_script.js ===
if (window == top) {
chrome.extension.onMessage.addListener(function(req, sender, sendMessage) {
console.log("Got request");
doStuff();
sendMessage('Done!');
});
}
=== manifest.json ===
{
"name": "My Extension",
"permissions": [
"declarativeContent", "activeTab"
],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"page_action": {
"default_icon": {
"19": "images/logo_19.png",
"38": "images/logo_38.png"
},
"default_title": "Do Something"
},
"manifest_version": 2
}