5

私はウェブサイト用の小さなGoogle Chrome拡張機能を作成しています。特定のページでいくつかのHTMLを変更したいと思います。history.pushStateでページが変更されたときにGoogle Chromeの拡張機能にコンテンツスクリプトを挿入するにはどうすればよいですか?

問題は、ウェブサイトが彼のコンテンツをajax経由で読み込んでおり、history.pushState APIを頻繁に使用していることです。私はページの最初の時間を開いたり、それをリロードしていたときに

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

すべてが正常に動作します: だから、私は、マニフェストにこの事を追加しました。 しかし、私がウェブサイトのページ間を移動するときに、「/ friends」ページにスクリプトを挿入しないでください。 URLが実際には変更されないため、これが起こっていると思います。彼らはhistory.pushState()を使用するので、chromeはスクリプトを挿入/再実行できません。

解決方法はありますか?

答えて

3

コンテンツスクリプトにwindow.onpopstateイベントを追加して待機することができます。イベントが発生すると、コンテンツスクリプトを再度実行できます。

参照

A)extension.sendMessage()

B)extension.onMessage().addListener

C)tabs.executeScript()

D)history.pushState()

E)window.onpopstate

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

manifest.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スクリプトの再実行のための背景ページに要求を送信

トラックコンテンツスクリプティングからのリクエスト用tと現在のページ

//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"); 

出力

enter image description here

は、あなたがより多くの情報が必要なら、私に教えてください。

+3

、pushStateは発生しません。 "popstate"イベントなので、このコードは機能しません。 –

7

私はこれを得ることができました。 Chrome Extension docs for webNavigationから:background.js

"permissions": [ 
    "webNavigation" 
    ], 

その後:

あなたはmanifest.jsonをwebNavigationの権限を設定する必要がところで

chrome.webNavigation.onHistoryStateUpdated.addListener(function(details) { 
     console.log('Page uses History API and we heard a pushSate/replaceState.'); 
     // do your thing 
    }); 
関連する問題