Akshay Khetrapal Akshay Khetrapal - 2 years ago 157
Javascript Question

How to trigger a function on specific websites from a chrome extension?

Recently started working with Chrome Extensions.
I am trying to figure out how I can execute a function on a specific website only.

For instance, I want to show an alert box on Stack Overflow only. I am using Chrome's Declarative Content API for this to match the host.

I haven't been able to find a similar question on SO for this.

My manifest.json file is running the following block of code in the background.

'use strict';

chrome.runtime.onInstalled.addListener(function() {
chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
conditions: [
new chrome.declarativeContent.PageStateMatcher({
pageUrl: {
hostEquals: 'stackoverflow.com'
actions: [new chrome.declarativeContent.SOOnlyFunction()]

function SOOnlyFunction()
alert('On SO');

Xan Xan
Answer Source

You can't use chrome.declarativeContent for anything but what's already built in as actions.

Which is currently specifically ShowPageAction, SetIcon and RequestContentScript (still experimental).

The reason that this can't be easily extended is because declarativeContent is implemented in native code as a more efficient alternative to JavaScript event handlers.

In general, chalk it up as an ambitious but essentially unviable/underdeveloped/abandoned idea from Chrome devs, similar fate to declarativeWebRequest.

See the other answer for implementation ideas using said JS handlers.

Or alternatively, you can still make it "declarative" by using content scripts declared in the manifest that will only activate on the predefined domain (as long as you know the domain in advance as a constant). They can then do something themselves or poke the event/background page to do something.

Finally, if your goal is to redirect/block the request, webRequest API is the one to look at.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download