简体   繁体   中英

Fire Event on Page Load

I am just getting started with Chrome Extensions. As an example I am using the "Page Redder" https://developer.chrome.com/extensions/samples#page-redder .

Because of chrome.browserAction.onClicked.addListener(function(tab) { it executes the red background when the browserAction button is clicked. How can I adjust this to make every page browsed to have a red background by default?

Here is full background.js file:

// Called when the user clicks on the browser action.
chrome.browserAction.onClicked.addListener(function(tab) {
  // No tabs or host permissions needed!
  console.log('Turning ' + tab.url + ' red!');
  chrome.tabs.executeScript({
    code: 'document.body.style.backgroundColor="red"'
  });
});

Here is the manifest:

{
  "name": "Page Redder",
  "description": "Make the current page red",
  "version": "2.0",
  "permissions": [
    "activeTab"
  ],
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "browser_action": {
    "default_title": "Make this page red"
  },
  "manifest_version": 2
}

The answer is Content Scripts; see the documentation and the architecture overview .

There are several ways to inject a content script: you're already using one of them, using chrome.tabs.executeScript . This is called programmatic injection , and allows you to run a content script at arbitrary time.

The other way is to register a content script in the manifest file . It will then always* be injected in matching pages. A simple example for your needs:

"content_scripts": [
  {
    "matches": ["*://*/*"],
    "js": ["redder.js"],
    "run_at": "document_end"
  }
],

where redder.js is:

document.body.style.backgroundColor="red";

* Note that it will only be injected if a page is (re)loaded after fully loading the extension. It will not inject into tabs existing at the moment of enabling the extension.


In fact, in your particular case you don't even have to use javascript. You can inject CSS instead:

"content_scripts": [
  {
    "matches": ["*://*/*"],
    "css": ["redder.css"],
    "run_at": "document_end"
  }
],

where redder.css is:

body {
  backgroundColor: red !important;
}

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