我正在制作一个显示通知的chrome扩展程序,当用户单击通知上的按钮时,它将通过background.js在新标签中打开一个html文件,我需要在api调用后对其进行修改,但是我无法找到一种通过我的background.js访问该页面的方法。
manifest.json权限"permissions": ["http://*/*", "https://*/*","notifications", "webNavigation", "storage", "tabs","activeTab", "background" ]
background.js的一部分
chrome.notifications.onButtonClicked.addListener(function() {
chrome.tabs.create({'url': 'index.html'}, (tab) => {
chrome.tabs.executeScript(tab,add_new_card());
});
});
function add_new_card(){
var elm= document.getElementById("cards");
console.log(document);
let new_card = '<div class="col-5 col-md-3 col-lg-2 p-0 mr-2 col"> ' +
'<div class="card"> ' +
'<a class="text-center" href=""> ' +
'<div class=" f-16 text-dark mt-4 card-title"> '+
'<strong class="text-capitalize">NEW CARD</strong> '+
'</div> </a> </div> </div> ';
elm.append(new_card);
}
我已经尝试了很多事情,但是我总是从document.getElementById(“ cards”)中得到null。
我还没有使用过“ executeScript”命令,因为我一直为此使用通用的内容脚本,但是据我在official documentation中所看到的,您需要将代码插入JS对象[ C0],而{ code: '<your_actual_code>' }
放在字符串中。
我有类似的问题,我只是使用window.open('','window_name')。对于单击按钮,我使该函数创建了新的弹出窗口,并为其命名。然后,我有另一个js文件,引用了相同的var existingWin = window.open('',“ window_name”)。从那里开始,所有我的Dom元素都使用existingWin.document.getElementsByClassName('whatever')进行引用。我不得不跳很多圈,因为正在打开的页面无法控制,所以我不得不四处挖掘并找到正确的框架和JavaScript上下文来进行工作。如果您控制index.html,则不应遇到此问题。