开发者

Pass variables to current tab via chrome extension

I am writing my first chrome extension, and I want to pass a variable to the currently opened tab and manipulate the DOM with it.

My extension has a button, and w开发者_运维知识库hen clicked, is executing this code:

chrome.tabs.getSelected(null, function(tab) {
 chrome.tabs.executeScript(tab.id, {
  file: 'tabscript.js'
 });
});

This works fine, but I see no way to pass a variable to tabscript.js so it can be used on the opened tab.


What do you need to pass a variable in to? Do you have a function you are calling in your script?

It must be noted that you don't have access to the pages Javascript, just the DOM.

If you have a particular function that you have to call with specific parameters then you should investigate content scripts and message passing.

Content scripts can get run on every page load (or a selection of pages), and you would use message passing to send a message from your extension button to the function in the content script.

Alternativly, and closer to your original idea you can construct the function you want to call at run time using the following:

chrome.tabs.getSelected(null, function(tab) {
 chrome.tabs.executeScript(tab.id, {
  code: 'function(){ ...... your code built dynamically ......}'
 });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜