单击Chrome扩展程序在浏览器操作上注入javascript和angular

时间:2016-03-25 16:04:27

标签: javascript jquery angularjs google-chrome-extension manifest

我有一个扩展,我只是将javascript注入任何页面,但是当我注入它时,我的角度模块和所有控制器都不起作用。我应该注射它们还是做其他事情?

injection.js

chrome.browserAction.onClicked.addListener(function (tab) {
    chrome.tabs.executeScript(tab.id, {
        file: 'src/injection.js'
    }, function () {
        console.log("Script injected!");
    });
});

app.js

angular.module('app', ['ngRoute', 'ui.router'])
    .run(function ($rootScope) {
        $rootScope.message = "Hello Angular again!";
        $rootScope.successMsg = "Hello Angular again! SUCCESS!";
});

injection.js

'use strict';
var cheapWatcherDiv = document.createElement('div');
cheapWatcherDiv.setAttribute('class', 'cheap-watcher');
document.body.appendChild(cheapWatcherDiv);
var logged = false;
if (logged == false) {
    $(".cheap-watcher").load(chrome.extension.getURL('views/main.html'));
    $('head').append('<link rel="stylesheet" href="' + chrome.extension.getURL('sass/main.css') + '" type="text/css" />');
} else {
    $(".cheap-watcher").load(chrome.extension.getURL('views/logoutTemplate.html'));
}

清单

...
"content_scripts": [
{
  "run_at": "document_end",
  "matches": [
    "http://*/*",
    "https://*/*"
  ],
  "js": [
    "lib/jquery/dist/jquery.min.js",
    "lib/angular/angular.js",
    "lib/angular-route/angular-route.min.js",
    "lib/ui-router/release/angular-ui-router.min.js",
    "lib/angular-sanitize/angular-sanitize.min.js",

    "src/app.js",
    "src/LoginController.js",
    "src/LogoutController.js",
    "src/MainController.js"
     ]
   }
 ]

1 个答案:

答案 0 :(得分:1)

在Google Chrome中,存在三种类型的脚本(Read More)。所有这些脚本都有自己的上下文。

在您的情况下,angularjs lib只能由内容脚本访问。如果你想在注入的脚本中访问angularjs和你的控制器,你也需要注入它们。注入时,请确保仅在加载上一个脚本时注入下一个脚本。

将其放在src/injection.js顶部

function injectJavaScripts(urls) {

    var elements = [];
    urls.forEach(function (url) {
        var s = document.createElement('script');
        s.src = chrome.extension.getURL(url);
        elements.push(s);
    });

    var target = document.head || document.documentElement;
    var i = 0;
    var patchNext = function () {
        if (i >= elements.length) return;
        else if (i > 0) {
            elements[i - 1].onload = null;
        } 

        elements[i].onload = patchNext;
        target.appendChild(elements[i]);

        i += 1;
    };

    patchNext();
};

injectJavaScripts([
    "lib/jquery/dist/jquery.min.js",
    "lib/angular/angular.js",
    "lib/angular-route/angular-route.min.js",
    "lib/ui-router/release/angular-ui-router.min.js",
    "lib/angular-sanitize/angular-sanitize.min.js",

    "src/app.js",
    "src/LoginController.js",
    "src/LogoutController.js",
    "src/MainController.js"
 ]);

请告诉我这是否适合您。