Sri*_*ram 4 javascript jquery google-chrome google-chrome-extension angularjs
我正在开发一个chrome扩展程序,它从用户正在浏览的网页上读取数据.我在上下文脚本中使用jQuery来从DOM获取数据.它在使用AngularJS的网站中期望的所有页面中按预期工作.该页面使用路由机制来加载连续的页面.但是当路由更改发生时,内容脚本不会重新加载.我正在使用Chrome webNavigation在background.js页面中收听onHistoryStateUpdated.
chrome.webNavigation.onHistoryStateUpdated.addListener(function(details) {
console.log(details);
chrome.tabs.sendMessage(details.tabId, {action: "open_dialog_box"}, function(response) {
});
});
Run Code Online (Sandbox Code Playgroud)
但是,即使在下一页的数据完全加载之前,此事件也会触发.我在开发者控制台中使用了以下代码,它可以正确地提供所请求的数据.
angular.element(document.getElementById('container')).injector().get('$rootScope')
Run Code Online (Sandbox Code Playgroud)
但是,当从内容脚本调用时,此injector()命令不起作用.我们如何从chrome扩展程序访问此进样器数据或根作用域?
谢谢
Chrome扩展程序内容脚本在单独的执行环境中运行.[官方文件]
因此,chrome扩展无法从内容脚本访问角度元素的范围元素.要访问它,我们需要从内容脚本中将脚本注入页面范围内,并使用事件侦听器传递数据.
首先创建需要在单独的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
}
}));Run Code Online (Sandbox Code Playgroud)
从内容脚本中在页面内部注入上述脚本
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);
});Run Code Online (Sandbox Code Playgroud)
现在使用此事件侦听器,您可以将数据从页面来回传递到内容脚本.
| 归档时间: |
|
| 查看次数: |
2549 次 |
| 最近记录: |