1

I'm going through the Google Chrome Extensions "Getting Started" tutorial, and I came across this code:

chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
  chrome.declarativeContent.onPageChanged.addRules([{
    conditions: [new chrome.declarativeContent.PageStateMatcher({
      pageUrl: {hostEquals: 'developer.chrome.com'},
    })
    ],
        actions: [new chrome.declarativeContent.ShowPageAction()]
  }]);
});

I looked at the "declarativeContent" API and this source: https://developer.chrome.com/extensions/declarativeContent#event-onPageChanged

However, I don't understand what action the "onPageChanged" represents. What "rules" are we modifying in this code? I understand this action only occurs when the host equals 'developer.chrome.com', but I can't figure out why we need the ".removeRules" portion.

zpChris
  • 98
  • 1
  • 8
  • I am going through the tutorial too. But when using this code snipped, and adding the permission, the action is not executed at all. The Page Action doesn't show. Did you need to do something different? – Eduardo Reis Apr 15 '20 at 18:51
  • That was a year ago, to be honest I don't remember -- sorry about that. – zpChris Apr 16 '20 at 14:18

1 Answers1

2

onPageChanged is a special event handler, from the doc:

The declarative event handlers provide a means to define rules consisting of declarative conditions and actions. Conditions are evaluated in the browser rather than the JavaScript engine which reduces roundtrip latencies and allows for very high efficiency.

onPageChanged provides you 3 methods with which you can work with rules:

  • addRules
  • removeRules
  • getRules

They are pretty self-explanatory. About your code:

chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {...})

all the 3 above functions implement the callback pattern, in the case of the removeRules, when the rule ids get deleted, the function specified executes. The first parameter the removeRules accepts is an array of rule ids or undefined if you want to delete all the currently active rules.

Marco Luzzara
  • 5,540
  • 3
  • 16
  • 42
  • Where can I find a list of the currently active rules that the "removeRules" function is deleting? I didn't even realize that there were any already-active rules. – zpChris Jun 19 '18 at 16:56
  • They might not do exist. Use `getRules` and you will find it out. – Marco Luzzara Jun 19 '18 at 17:03
  • How could I program a lazy hostEquals inside the PageStateMatcher? – Sornii Aug 23 '18 at 16:11
  • @Sornii Please explain your "*lazy*". – Marco Luzzara Aug 23 '18 at 19:14
  • @MarcoLuzzara It's not possible. I was talking about a custom javascript function in the page state matcher. I found that is not possible because these functions are turned into the browser language so that code can run faster than javascript. – Sornii Oct 01 '18 at 20:54