在 chrome.tabs.executeScript 中,如何调用参数驻留在内容脚本中的函数?
考虑以下代码:
function SwapColumns() {
chrome.tabs.executeScript(null,
{code:"SwapNameAndSurname();"});
}
上面的代码位于 popup.html 中,方法 SwapNameAndSurname() 位于名为 js.js 的内容脚本中,该脚本只包含一个充满函数的库。当我从 popup.html 调用 SwapColumns 函数时,js.js 中的 SwapNameAndSurname() 函数被调用,通过内容脚本的力量更改原始页面 DOM 中的某些内容。
然而我的问题就在这里。我在 popup.html 中准备了一个名为 employee 的对象,我需要将其作为参数发送到 SwapNameAndSurname() 函数:
var employee = {'Name' : 'John', 'Surname' : 'Doe', 'Qualifications' : [{'Title':'MCAD', 'Date':'Jan 2008'},{'Title':'MCSA', 'Date':'Feb 2008'}]};
function SwapColumns() {
chrome.tabs.executeScript(null,
{code:"SwapNameAndSurname(**???employee???**);"});
}
我该怎么做?由于在 chrome.tabs.executeScript 中您必须直接将代码写入字符串,因此您无法真正发送参数。我已阅读 Chrome 的 tabs.executeScript - 传递参数和使用库?< /a> 但仍然无法弄清楚发生了什么。
Consider this code:
function SwapColumns() {
chrome.tabs.executeScript(null,
{code:"SwapNameAndSurname();"});
}
The code above is in popup.html, the method SwapNameAndSurname() is in a content script named js.js that contains nothing but a library full of functions. When I call the SwapColumns function from popup.html, the SwapNameAndSurname() function in js.js is called changing something in the DOM of the original page via the power of content scripts.
However my problem is here. I have prepared an object named employee in popup.html that I need to send to the SwapNameAndSurname() function as a parameter:
var employee = {'Name' : 'John', 'Surname' : 'Doe', 'Qualifications' : [{'Title':'MCAD', 'Date':'Jan 2008'},{'Title':'MCSA', 'Date':'Feb 2008'}]};
function SwapColumns() {
chrome.tabs.executeScript(null,
{code:"SwapNameAndSurname(**???employee???**);"});
}
How can I do that? Since in chrome.tabs.executeScript you have to write code directly into a string, you cannot really send parameters. I've read Chrome's tabs.executeScript - passing parameters and using libraries? but still can't figure out what's happening.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我找到了我自己问题的答案。在扩展页面中,您必须调用 chrome.tabs.sendRequest 方法,在内容脚本中,您必须使用 chrome.extension.onRequest.addListener 方法添加侦听器。发送请求方法将触发内容脚本中的事件,使您能够将任何形式的数据发送到内容脚本。
有关进一步参考,请参阅 http://aarongusman.wordpress.com/2011/03/30/communication- Between-chrome-extension-content-scripts-and-extension-pages/
I found an answer to my own question. From the extension pages you have to call the chrome.tabs.sendRequest method and from the the content scripts you have to add a listener using the chrome.extension.onRequest.addListener method. The send request method will trigger the event found in the content scripts enabling you to send any form of data to the content script.
For further reference see http://aarongusman.wordpress.com/2011/03/30/communication-between-chrome-extension-content-scripts-and-extension-pages/