2015-09-17 33 views
2

我正在使用两个按钮进行扩展:开始和停止。点击开始按钮的HTML页面,应该开始刷新特定的计时器后,并在点击停止它应该停止刷新。Content.js脚本从不调用表格行和刷新页面

在每次刷新后,HTML页面中都有一个表格,用id myTable.So表示,我想要这个表格的行数。

为了得到这个我没有这样的事:

首先用于弹出,我做了popup.js

window.onload = function() { 
document.getElementById("startbutton").onclick = function() { 
    chrome.extension.sendMessage({ 
     type: "table-row-count_start" 
    }); 
} 
document.getElementById("stopbutton").onclick = function() { 
    chrome.extension.sendMessage({ 
     type: "table-row-count_stop" 
    }); 
} 
} 

在background.js

chrome.extension.onMessage.addListener(function(request, sender, sendResponse) { 
switch(request.type) { 
    case "table-row-count_start": 
     alert("Refershing started"); 
     RefreshAndCount(); 
     break; 
    case "table-row-count_stop": 
     alert("Stop Refershing"); 
     break; 
} 
return true; 
}); 

var RefreshAndCount = function(){ 
chrome.tabs.getSelected(null, function(tab){ 
    chrome.tabs.sendMessage(tab.id, {type: "table-row-count"}); 
    chrome.browserAction.setBadgeText({text: "Counting!"}); 
}); 
} 

这将使呼叫content.js,因为我们需要与HTML页面的DOM进行交互。在这个脚本中,我做了这样的事情:

chrome.extension.onMessage.addListener(function(message, sender, sendResponse) { 
switch(message.type) { 
    case "table-row-count": 
     var x = document.getElementById("myTable").rows.length; 
     alert("Row count = " + x); 
     var Refresh = confirm("Do you want to refresh the page?"); 
     if (Refresh) 
     { 
      setTimeout("location.reload(true);",5000); 
     } 
    break; 
} 
}); 

脚本content.js永远不会被调用。我不知道这是为什么。请帮忙。 也只会刷新一次,固定定时器后如何保持引用。

下面是manifest.json的

{ 
"name": "Refresher", 
"version": "0.0.1", 
"manifest_version": 2, 
"description" : "Refresh the site contents after a while", 
"icons": { "32": "icon.jpg" }, 
"browser_action": { 
    "default_icon": { "32": "icon.jpg" }, 
    "default_title": "Refersher", 
    "default_popup": "browseraction/popup.html" 
}, 
"background": { 
    "scripts": ["background.js"], 
    "persistent": true 
}, 
"content_scripts": [{ 
    "matches": ["http://www.w3schools.com/html/tryit.asp?filename=tryhtml_table"], 
    "js": ["content.js"] 
}] 
} 
+0

将'manifest.json'添加到问题中。 – wOxxOm

+0

@ wOxxOm新增。请帮忙 – GitCoder

回答

0

在这种情况下,你已经使用了过时chrome.tabs.getSelected这回错了标签ID为-1所以邮件从未发送并显示在控制台中的错误。

使用chrome.tabs.query

var RefreshAndCount = function() { 
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { 
     chrome.tabs.sendMessage(tabs[0].id, {type: "table-row-count"}); 
     chrome.browserAction.setBadgeText({tabId: tabs[0].id, text: "Counting!"}); 
    }); 
}; 

同样要注意setBadgeText是只用于指定的标签。

N.B. Always,always使用调试器来检查什么是错误的。因此,您可以停止使用alert并开始使用console.log或在调试器中检查/观察变量。

+0

引用到停止,不止一次。 – GitCoder

+0

我不明白是什么问题。你是否已经删除了'alert'并尝试了一些像调试? – wOxxOm

+0

是的,我做到了。现在调用contetn.js,但它给出了这个:runtime.onMessage的事件处理程序中的错误:TypeError:无法读取null的属性'行'。什么是理由?假设我的页面上只有一个表格,可以这样做,这样我就不需要像在这里那样硬编码表格的id了var x = document.getElementById(“myTable”)。rows.length ; – GitCoder