从浏览器扩展调用网页JavaScript方法

我正在使用webExtensions开发一个firefox扩展,它可以帮助我轻松完成下面的场景。

我必须点击网站上大约50-60个按钮来更新任务状态。 单击此按钮,网页将调用网页的updTask(id) JavaScript函数,然后进行Web服务调用以更新任务。

我无法使用以下代码从我的内容脚本中执行此操作:

manifest.json

 "permissions": [ "activeTab", "cross-domain-content": ["http://workdomain.com/","http://workdomain.org/","http://www.workdomain.com/","http://www.workdomain.org/"] ] 

内容脚本代码:

 function taskUpdate(request, sender, sendResponse) { console.log(request.start + 'inside task update'); updateTask(45878); chrome.runtime.onMessage.removeListener(taskUpdate); } function updateTask(id) { //TODO: code to get all buttons and task id's updTask(id); // Not working } 

插件脚本:

 document.addEventListener("click", function(e) { if (e.target.classList.contains("startButton")) { chrome.tabs.executeScript(null, { file: "/content_scripts/taskUpdate.js" }); chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { chrome.tabs.sendMessage(tabs[0].id, {start: "start"}); }); return; } else if (e.target.classList.contains("clear")) { chrome.tabs.reload(); window.close(); return; } }); 

有人能指出我正确的方向,我在这里失踪了什么?

您的内容脚本与页面脚本(网页中已存在的脚本)的上下文/范围不同。 您的内容脚本具有比授予页面脚本更高的权限。 保持内容脚本与页面脚本分离是浏览器扩展的常规体系结构,这是出于安全原因而完成的。

为了在页面脚本上下文中执行代码,您必须创建元素并将其插入到页面的DOM中。

你可以这样做:

 function updateTask(id) { let newScript = document.createElement('script'); newScript.innerHTML='updTask(' + id + ');'; document.head.appendChild(newScript); //newScript.remove(); //Can be removed, if desired. } 

添加的脚本在页面上下文中运行,因为它现在是DOM中的元素。 浏览器识别出添加了元素并在插入它的脚本不再处理时对其进行评估(执行包含的代码)。 对于添加到DOM的任何其他元素,它基本上都是一样的。 因为它是页面的一部分,所以gets内部的代码在页面脚本上下文/范围中运行。

从内容脚本在页面上下文中执行的通用代码

维护要在页面上下文中执行的代码的最简单方法是将其作为函数写入内容脚本,然后将该函数注入页面上下文。 下面是一些通用代码,它们将参数传递给您在页面上下文中执行的函数时执行此操作:

此实用程序函数executeInPage()将在页面上下文中执行函数,并将任何提供的参数传递给函数。 参数必须是ObjectArrayfunctionRegExpDate和/或其他基元 ( Booleannull , undefined , NumberString ,但不是Symbol )。

 /* executeInPage takes a function defined in this context, converts it to a string * and inserts it into the page context inside a  

使用excuteInPage()

 function logInPageContext(arg0,arg1,arg2,arg3){ console.log('arg0:', arg0); console.log('arg1:', arg1); console.log('arg2:', arg2); console.log('arg3:', arg3); } executeInPage(logInPageContext, false, '', 'This', 'is', 'a', 'test'); /* executeInPage takes a function defined in this context, converts it to a string * and inserts it into the page context inside a