我正在创建Chrome扩展程序,点击扩展程序图标后会向用户显示一个按钮,单击该按钮将打开一个新选项卡,该选项卡将显示从原始页面传递给它的参数。奇怪的是,如果我调试它,这将起作用(即右键单击扩展图标并单击“Inspect popup”),但如果我没有调试,它只会在单击按钮时显示空白页。
的manifest.json
{
"name": "test name",
"version" : "0.1",
"description": "test description",
"browser_action":
{
"default_icon": "icon_128.png",
"popup": "test.html"
},
"permissions": [
"tabs", "http://*/*", "https://*/*"
]
}
的test.html
<HTML>
<BODY>
<script type="text/javascript">
var currentWindowID = -1;
window.onload = function(e){
chrome.windows.getCurrent(function(w)
{
currentWindowID = w.id;
});
}
function openNextPage(){
console.log("in openNextPage");
chrome.tabs.create(
{url: "test2.html"},
function(tab)
{
chrome.tabs.sendRequest(tab.id, {someParam: currentWindowID});
}
);
console.log("exiting openNextPage");
}
</script>
<input type="button" value="Show next page" onClick="openNextPage()">
</BODY>
</HTML>
test2.html
<HTML>
<script type="text/javascript">
chrome.extension.onRequest.addListener(function(request)
{
document.write("<h1>test</h1>");
document.write("<h2>value=" + request.someParam + "</h2>");
});
</script>
</HTML>
答案 0 :(得分:2)
浏览器将在创建新标签页时激活,弹出窗口将关闭。因此,永远不会从chrome.tabs.create
调用回调。背景页面是这种代码的更合适的地方。
的test.html
<HTML>
<BODY>
<script type="text/javascript">
var currentWindowID = -1;
window.onload = function(e){
chrome.windows.getCurrent(function(w)
{
currentWindowID = w.id;
});
}
function openNextPage() {
var bg = chrome.extension.getBackgroundPage();
bg.openNextPage(currentWindowID);
}
</script>
<input type="button" value="Show next page" onClick="openNextPage()">
</BODY>
</HTML>
background.html
<HTML>
<BODY>
<script type="text/javascript">
function openNextPage(currentWindowID) {
console.log("in openNextPage");
chrome.tabs.create(
{url: "test2.html"},
function(tab)
{
chrome.tabs.sendRequest(tab.id, {someParam: currentWindowID})
}
);
console.log("exiting openNextPage");
}
</script>
</BODY>
</HTML>