2015-02-24 41 views
0

我正在研究主要在弹出窗口中工作的Chrome扩展。 我希望用户在弹出窗口中的输入字段中输入一些文本(字符串),并且该字符串将用作我希望在特定页面上注入并运行的脚本中的“变量”。在注入内容脚本之前传递变量

我试图通过使内容脚本,将执行该脚本,使用下面的有据可查的方式实现这一目标:

var s = document.createElement('script'); 


s.src = chrome.runtime.getURL('pageSearch.js'); 
s.onload = function() { 
    this.parentNode.removeChild(this); 
}; 

(document.head||document.documentElement).appendChild(s); 

基本上,我想所有的方式将用户的输入代码在page.js中执行页面上的脚本之前。

什么是最好的方法来解决这个问题?我不会收到任何有关扩展的信息。

谢谢。

+0

的可能重复的[Chrome扩展 - 消息从弹出传递到内容脚本](http://stackoverflow.com/questions/ 6108906/Chrome扩展消息传递从弹出到内容脚本) – levi 2015-02-24 20:25:32

+0

嘿,谢谢。这恐怕不能解决这个问题。 – 2015-02-25 07:38:11

回答

2

要将变量从弹出窗口传递到动态插入的内容脚本,请参见Pass a parameter to a content script injected using chrome.tabs.executeScript()

在获取内容脚本中的变量后,有很多方法可以将变量获取到页面中的脚本。

E.g.通过在脚本标签上设置属性,并使用document.currentScript来访问此<script>标签。注:document.currentScript仅在文档中插入标签后立即引用脚本标签。如果您稍后想要引用原始脚本标记(例如,在计时器或事件处理程序中),则必须将对脚本标记的引用保存在局部变量中。

内容的脚本:

var s = document.createElement('script'); 
s.dataset.variable = 'some string variable'; 
s.dataset.not_a_string = JSON.stringify({some: 'object'}); 
s.src = chrome.runtime.getURL('pageSearch.js'); 
s.onload = function() { 
    this.remove(); 
}; 
(document.head||document.documentElement).appendChild(s); 

pageSearch.js:

(function() { 
    var variable = document.currentScript.dataset.variable; 
    var not_a_string = JSON.parse(document.currentScript.dataset.not_a_string); 
    // TODO: Use variable or not_a_string. 
})(); 
+0

嗨,罗布,这正是我需要的缺失部分。我在整个网站上的其他评论也对我的学习有很大的帮助。非常感谢你。 – 2015-02-25 16:36:36

+0

@BorisAblamunits不客气! – 2015-02-25 17:34:19