如何从chrome扩展访问angularjs根范围

How to access angularjs root scope from chrome extension

本文关键字:angularjs 范围 访问 扩展 chrome      更新时间:2023-09-26

我正在开发一个chrome扩展,它可以从用户浏览的网页中读取数据。我在上下文脚本中使用jQuery从DOM中获取数据。它在使用AngularJS的网站中的所有页面中都能正常工作。页面使用路由机制加载连续页面。但当发生此路由更改时,内容脚本不会重新加载。我正在使用Chrome网络导航来收听background.js页面中的onHistoryStateUpdated。

chrome.webNavigation.onHistoryStateUpdated.addListener(function(details) {
    console.log(details);
    chrome.tabs.sendMessage(details.tabId, {action: "open_dialog_box"}, function(response) {
    });
});

但此事件甚至在下一页的数据完全加载之前就触发了。我在开发人员控制台中使用了以下代码,它正确地提供了请求的数据。

angular.element(document.getElementById('container')).injector().get('$rootScope')

但是,当从内容脚本调用此injector()命令时,该命令不起作用。我们如何从chrome扩展访问这个注入器数据或根作用域?

谢谢

Chrome扩展内容脚本在单独的执行环境中运行。【官方文件】

因此chrome扩展无法从内容脚本访问angular元素的scope元素。要访问它,我们需要从内容脚本将脚本注入页面范围内,并使用事件侦听器传递数据。

首先在一个单独的JS文件中创建需要访问根作用域的脚本。

angular_inject.js

var $rootScope = angular.element(document.getElementById('midd-container-inner')).injector().get('$rootScope');
var currval = $rootScope.data['id'];			
document.dispatchEvent(new CustomEvent('RW759_connectExtension', {
	detail: {
		id: currval
	}
}));

从内容脚本在页面内注入上述脚本

content_script.js

var s = document.createElement('script');
s.src = chrome.extension.getURL('scripts/angular_inject.js');
(document.head||document.documentElement).appendChild(s);
s.onload = function() {
    s.parentNode.removeChild(s);
};
// Event listener
document.addEventListener('RW759_connectExtension', function(e) {
    // e.detail contains the transferred data (can be anything, ranging
    // from JavaScript objects to strings).
    // Do something, for example:
	console.log(e.detail);
});

现在,使用这个事件侦听器,您可以在页面到内容脚本之间来回传递数据。