Interface WebAnalytics

  • @ServerSide
    public interface WebAnalytics
    Extension point to support a web analytics tool like Matomo or Google Analytics in the webapp.

    See the method getUrlPathToJs() for the details about specification.

    Example of implementation with a WebService:

     import java.nio.charset.StandardCharsets;
     import org.sonar.api.web.WebAnalytics;
     public class MyWebAnalytics implements WebAnalytics, WebService, RequestHandler {
       public String getUrlPathToJs() {
         return "api/myplugin/analytics";
       public void define(Context context) {
         NewController controller = context.createController("api/myplugin");
       public void handle(Request request, Response response) throws IOException {
         try (OutputStream output =
           .output()) {
           IOUtils.write("{replace with the javascript content}", output, StandardCharsets.UTF_8);
    • Method Detail

      • getUrlPathToJs

        java.lang.String getUrlPathToJs()
        Returns the URL path to the Javascript file that will be loaded by the webapp. File must be provided by SonarQube server and can't be located outside.

        The returned path must not start with a slash '/' and must not contain ".." or "://".


        • "api/google/analytics" if file is generated by a WebService.
        • "static/myplugin/analytics.js" if file is bundled with the plugin with key "myplugin" (note that in this case the file in the plugin JAR is "static/analytics.js").

        Webapp does not load the Javascript file if the URL does not return HTTP code 200.

        The Javascript file is composed of two parts:

        • the global code that is executed when the browser loads the webapp
        • the handler that is executed by the webapp when page is changed. See function "window.setWebAnalyticsPageChangeHandler()".

        Example for Matomo:
         var _paq = window._paq || [];
         // tracker methods like "setCustomDimension" should be called before "trackPageView"
         (function() {
           var u = "";
           _paq.push(["setTrackerUrl", u + "matomo.php"]);
           _paq.push(["setSiteId", "12345"]);
           var d = document,
             g = d.createElement("script"),
             s = d.getElementsByTagName("script")[0];
           g.type = "text/javascript";
           g.async = true;
           g.defer = true;
           g.src = "//";
           s.parentNode.insertBefore(g, s);
         window.setWebAnalyticsPageChangeHandler(function(pathname) {
           _paq.push(["setCustomUrl", pathname]);
           _paq.push(["setDocumentTitle", document.title]);