javascript闪卡

时间:2013-03-21 17:27:08

标签: javascript jquery google-chrome google-chrome-extension

有人可以告诉我为什么以下扩展不起作用?我试图用脚本src =“...”/ script替换内联脚本,但它仍然不起作用。是否最好在内容脚本中列出两个javascripts或将它们同时删除?

POPUP.html

<!DOCTYPE html> 
<html>
<head>
<style>
  body { width: 300px; }
  textarea { width: 250px; height: 100px;}
</style>
<script>
  function pasteSelection() {
  chrome.tabs.getSelected(null, function(tab) {
  chrome.tabs.sendRequest(tab.id, {method: "getSelection"}, function (response) {
  var text = document.getElementById('text'); 
  text.innerHTML = response.data;
    });
  });
 }
</script>
</head>
<body>
<textarea id="text"> </textarea>
<button onclick="pasteSelection(); ">Paste Selection</button>
</body>
</html>

selection.js

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.method == "getSelection")
  sendResponse({data: window.getSelection().toString()});
else
  sendResponse({}); // snub them.
});

的manifest.json

{
 "name": "Selected Text",
 "version": "0.1",
 "description": "Selected Text",
 "browser_action": {
 "default_title": "Selected Text",
 "default_icon": "online.png",
 "default_popup": "popup.html" 
},
 "permissions": [
 "tabs",
 "chrome://favicon/",
 "http://*/*", 
 "https://*/*"
],
 "content_scripts": [
{
"matches": ["http://*/*"],
"js": ["selection.js", "paste.js"]
"run_at": "document_start",
"all_frames": true
}
]
}

1 个答案:

答案 0 :(得分:0)

您不能使用任何内联代码,并且您正在使用多种折旧方法。不将所有内联代码移动到外部文件可能是导致问题的原因,但无论如何使用折旧方法并不好。修复它会使它看起来像这样:

<强> Popup.html

<!DOCTYPE html> 
<html>
  <head>
    <style>
      body { width: 300px; }
      textarea { width: 250px; height: 100px;}
    </style>
    <script src="popup.js"></script>
  </head>
  <body>
    <textarea id="text"> </textarea>
    <button id="pasteButton">Paste Selection</button>
  </body>
</html>

<强> Popup.js

window.onload = function() {
  var pasteButton = document.getElementById("pasteButton");
  pasteButton.onclick = function(){
    chrome.tabs.query({active:true,currentWindow:true}, function(tab) {
      chrome.tabs.sendMessage(tab[0].id,{method:"getSelection"},function(response){
        var text = document.getElementById('text'); 
        text.innerHTML = response.data;
      });
    });
  };
};

<强> selection.js

chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
  if (request.method == "getSelection")
    sendResponse({data: window.getSelection().toString()});
  else
    sendResponse({}); // snub them.
});

<强>的manifest.json

{
 "name": "Selected Text",
 "version": "0.1",
 "description": "Selected Text",
 "manifest_version": 2,
 "browser_action": {
   "default_title": "Selected Text",
   "default_icon": "online.png",
   "default_popup": "popup.html" 
 },
 "permissions": [
   "tabs",
   "chrome://favicon/",
   "http://*/*", 
   "https://*/*"
 ],
 "content_scripts": [{
   "matches": ["http://*/*"],
   "js": ["selection.js", "paste.js"],
   "run_at": "document_start",
   "all_frames": true
 }]
}