【问题标题】:AngularJS components to build Chrome ExtensionAngularJS 组件构建 Chrome 扩展
【发布时间】:2017-11-09 20:52:50
【问题描述】:

我正在构建一个 Chrome 扩展程序,令人惊讶的是,我可以为扩展程序端创建一个 AngularJS 应用程序,为内容脚本端创建另一个应用程序。后者对于处理页面中注入的类似模式的元素很有用。我用这个内容脚本注入了这个应用程序:

var myApp = angular.module('ContentApp', []);
/**
 * Append the app to the page.
 */
$.get(chrome.runtime.getURL('templates/modal.html'), function(data) {
  $($.parseHTML(data)).appendTo('body');

  // Manually bootstrapping AngularJS app because template was also manually imported.
  angular.element(document).ready(function() {
    angular.bootstrap(document, ['ContentApp']);
  });
});

现在问题来了,modal.html 越来越大,我仍然需要添加更多元素。我认为我可以开始在 Angular 中创建组件并这样做:

angular.module('ContentApp').
  component('greetUser', {
    template: 'Hello, {{$ctrl.user}}!',
    controller: function GreetUserController() {
      this.user = 'world';
    }
  });

这确实有效。我可以在呈现的页面中看到Hello, world 消息。但是当我将template 更改为templateUrl 时,它失败了:

// This doesn't work
templateUrl: 'templates/component.html',

// Neither does this
templateUrl: 'templates/component.html',

// Although this is similar to the way I got the main template, it didn't worked either
templateUrl: chrome.runtime.getURL('templates/component.html'),

值得一提的是我添加了manifest.json的权限:

  "web_accessible_resources": [
    "templates/*"
  ],

我在控制台中得到的错误是这样的:

Error: [$sce:insecurl] http://errors.angularjs.org/1.5.11/$sce/insecurl?p0=chrome-extension%3A%2F%2Fext_id%2Ftemplates%2Fmodal.html
    at chrome-extension://ext_id/scripts/lib/angular.min.js:6:426
    at getTrusted (chrome-extension://ext_id/scripts/lib/angular.min.js:154:156)

有人知道如何让它工作吗?还是我对 Chrome 扩展的要求太高了?

【问题讨论】:

标签: angularjs google-chrome-extension angularjs-components


【解决方案1】:

我在this link 中找到了答案。感谢faboolous 为我指明了正确的方向;)

由于templateURL 是在$scope 执行之前处理的,因此在Chrome 扩展程序中保护模板路径的正确方法是:

// This works. Yay!
    angular.module('ContentApp').
      component('greetUser', {
        templateUrl: ['$sce', function ($sce) {
          return $sce.trustAsResourceUrl(chrome.runtime.getURL('templates/component.html'));
        }],
        controller: function ($scope) {
    ...

【讨论】:

    猜你喜欢
    • 2023-03-10
    • 2016-10-30
    • 2010-11-16
    • 1970-01-01
    • 1970-01-01
    • 2018-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多