11

ウェブサイト用の小さなグーグルクローム拡張機能を作成していますが、特定のページのHTMLを変更したいと思います。

問題は、Webサイトがajaxを介してコンテンツをロードし、history.pushStateAPIを頻繁に使用することです。だから、私はマニフェストにこのことを追加しました:

"content_scripts": [
   {
     "matches": ["http://vk.com/friends"],
     "js": ["js/lib/jquery.min.js", "js/friends.js"],      
   },
 ]

初めてページを開いたり、ページをリロードしたりすると、すべて正常に機能します。しかし、ウェブサイトのページ間を移動しているとき、chromeは「/friends」ページにスクリプトを挿入しません。これは、URLが実際には変更されていないためだと思います。それらはhistory.pushState()を使用するため、chromeはスクリプトを再度挿入/再実行できません。

これに対する解決策はありますか?

4

2 に答える 2

14

私はこれを機能させることができました。webNavigationのChrome拡張機能のドキュメントから:

マニフェスト.jsonwebNavigationで権限を設定する必要があります:

  "permissions": [
     "webNavigation"
  ],

次に、background.jsで:

  chrome.webNavigation.onHistoryStateUpdated.addListener(function(details) {
        console.log('Page uses History API and we heard a pushSate/replaceState.');
        // do your thing
  });
于 2013-07-11T03:26:31.797 に答える
7

コンテンツスクリプトにwindow.onpopstateイベントを追加してリッスンできます。イベントが発生したら、コンテンツスクリプトを再実行できます。

参考文献

a) extension.sendMessage()

b) extension.onMessage()。addListener

c) tabs.executeScript()

d) history.pushState()

e) window.onpopstate

サンプルデモンストレーション:

マニフェスト.json

コンテンツスクリプトが挿入されたURLと、すべてのAPIのタブがマニフェストファイルで十分な権限を持っていることを確認します

{
    "name": "History Push state Demo",
    "version": "0.0.1",
    "manifest_version": 2,
    "description": "This demonstrates how push state works for chrome extension",
    "background":{
        "scripts":["background.js"]
    },
    "content_scripts": [{
        "matches": ["http://www.google.co.in/"],
        "js": ["content_scripts.js"]
     }],
    "permissions": ["tabs","http://www.google.co.in/"]
}

content_scripts.js

onpopstateイベントを追跡し、スクリプトの再実行のためにバックグラウンドページにリクエストを送信します

window.onpopstate = function (event) {
    //Track for event changes here and 
    //send an intimation to background page to inject code again
    chrome.extension.sendMessage("Rerun script");
};

//Change History state to Images Page
history.pushState({
    page: 1
}, "title 1", "imghp?hl=en&tab=wi");

background.js

コンテンツスクリプトからのリクエストを追跡し、スクリプトを実行して現在のページに移動します

//Look for Intimation from Content Script for rerun of Injection
chrome.extension.onMessage.addListener(function (message, sender, callback) {
    // Look for Exact message
    if (message == "Rerun script") {
        //Inject script again to the current active tab
        chrome.tabs.executeScript({
            file: "rerunInjection.js"
        }, function () {
            console.log("Injection is Completed");
        });
    }
});

rerunInjection.js

いくつかの些細なコード

console.log("Injected again");

出力

ここに画像の説明を入力してください

さらに情報が必要な場合はお知らせください。

于 2012-12-11T08:33:59.560 に答える