1

重複の可能性:
Chrome拡張機能の遅延状態

拡張機能の初心者で、あちこちからコードを収集することで、タブのURL(特定のWebサイトで機能)を収集し、データベースに保存するためにajaxImを使用してサーバーに送信する簡単なコードを作成しました。私がやろうとしているのは、タイマーを追加して、前のクリックが5秒以内に発生した場合にブラウザーボタンが無効になる(または何もしない)ようにすることです。

以下は拡張機能の構造です。

マニフェスト:

{
"name": "The name",
"icons": { "16": "Big.png",
       "48": "Big.png",
       "128": "Big.png" },
"version": "1.0",
"manifest_version": 2,
"description": "and the description",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": ["tabs", "<all_urls>"]
}

popup.js:

chrome.tabs.getSelected(null,function(tab) {
var Mp=tab.url
if(Mp=='http://www.examplesite.com')
{
var xhr=new XMLHttpRequest();
var Params;
xhr.open("POST", "http://myserver.com/post_from_extension.asp", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
Params='Url=' + tab.url;
xhr.onreadystatechange=function()
    {
        if(xhr.readyState==4)
        {
        message.innerHTML=xhr.responseText;
        }
    }
xhr.send(Params);
}
else
{
message.innerHTML='<span style="font-family: Segoe UI, Tahoma;color: #f00">This is not a valid url</span>';
}
});

popup.html

<!DOCTYPE html>
<html style=''>
<head>
<script src='popup.js'></script>
</head>
<body style="width:400px;">
<div id='message'><span style="font-family: Segoe UI, Tahoma;color: #00f">Sending request</span></div>
</body>
</html>

副次的な質問として、Ajaxを使用しない場合、データベースにURLを投稿する他の方法はありますか?

私を読んでくれてありがとう。

4

1 に答える 1

1

拡張機能にバックグラウンド ページ (スクリプト) を追加する必要があると思います。これは一種のアプリケーション状態です。これをマニフェストに追加します。

"background": {
    "scripts": ["background.js"]
  },

次に、ページで、各タブに対してブラウザー アクションが最後に実行された時刻を格納する配列を定義できます。

var timers = [];

この配列の要素を、popup.jsそのようなものから更新できます(getSelectedコールバックで):

chrome.extension.getBackgroundPage().timers[tabId] = new Date();
chrome.browserAction.disable(tabId);
chrome.browserAction.setIcon({path: "icon-disabled.png", tabId: tabId});

ブラウザのアクションを無効にして、その外観を無効/グレー表示に変更する方法に注意してください。

登録された時間から 5 秒を超える時間が経過したら、バックグラウンド ページからボタンを再度有効にする必要があります。

var currentTime = new Date();
if(currentTime - chrome.extension.getBackgroundPage().timers[tabId] > 5000)
{
  chrome.browserAction.enable(tabId);
  chrome.browserAction.setIcon({path: "icon-enabled.png", tabId: tabId});
}

このコードは、コールバックから配列setInterval内のすべての要素を循環して実行できます。timers

于 2012-12-29T15:14:19.873 に答える