简体   繁体   中英

chrome extensions - Content Scripts on demand

I wrote my small extension for Chrome which works in the context of the webpage.

Everything is fine, except that code is executed every time when I visit URL defined in the manifest.json in content-scripts matches.

What I would like is to launch it manually - 'on demand' - after clicking on the icon of the extension next to the url bar.

Is this possible?

Yes - it is possible. I've took it from: http://developer.chrome.com/extensions/content_scripts.html

The relevant part is: "...To insert code into a page, your extension must have cross-origin permissions for the page. It also must be able to use the chrome.tabs module. You can get both kinds of permission using the manifest file's permissions field. Once you have permissions set up, you can inject JavaScript into a page by calling executeScript()..."

/* in background.html */
chrome.browserAction.onClicked.addListener(function(tab) {
  chrome.tabs.executeScript(null,
    {code:"document.body.bgColor='red'"});
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM