将当前网页的网址显示为Chrome扩展程序

时间:2014-04-13 23:40:53

标签: javascript google-chrome-extension

我尝试在Chrome扩展程序中显示当前网页的网址。我刚刚开始javascript和chrome扩展开发。

我的manifest.json

{
"manifest_version": 2,
"version": "0.1",
"name": "!!!",
"author": "!!!",
"description": "Extension !!!",
"icons": {
    "default_icon": "logo2.png"
},
"browser_action": {
    "default_icon": "logo2.png",
    "default_popup": "popup.html"
},
"options_page": "options.html",
"background": {
    "scripts": ["background.js"],
    "persistent": true
},
"content_scripts": [{
    "matches": ["http://*/*", "https://*/*"],
    "js": ["contentscript.js"]
}],
"web_accessible_resources": ["contentscript.js"],
"permissions": ["tabs", "http://*/*", "https://*/*"]
}

我的popup.html:

<!doctype html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<title>Extension !!!!!!!!!</title>
<link rel="stylesheet" href="stylesheet.css">
<!--<script type="text/javascript" src="tracker.js"> </script>
<script src="canvas.js"></script>-->
<script src="background.js"></script>
<script src="contentscript.js"></script>
</head>
<body>

    <!--=========TITLE============== -->
    <div id="main-logo">        
        <div id="logo"><img src="logo2.png"><img></div>
        <h1>!!!!</h1>
    </div>

    <div id="main">
        <!--=============Display URL===========-->
        <div id="main-url">
            <script src="background.js"></script>
                    </div>
            </div>

我的contentscript.js

chrome.extension.sendRequest({
url: window.location.href
}, function(response) {
console.log(response.farewell);
);

我的background.js

chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
    console.log(sender.tab ?
        "from a content script:" + sender.tab.url :
        "from the extension !!TEST!!");
}
);

我的弹出窗口和控制台中没有任何东西......

感谢您的帮助 最好的问候

1 个答案:

答案 0 :(得分:1)

不推荐使用chrome.extension.sendRequest。你应该使用chrome.runtime.sendMessage:

<强>发件人

chrome.runtime.sendMessage({
  url: window.location.href
}, function(response) {
  console.log(response.farewell);
);

<强>接收机

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if(request.url==="http://xxxxx.com"){
        chrome.runtime.sendMessage({farewell:"bingo"},function(response){});
    }
  }
);
顺便说一句,正如@Teepeemm所说,你不必两次加载内容脚本和背景js。根据匹配模式将contentscript.js注入到Web上下文中。并且在扩展开始运行后将执行background.js