タブ(Chrome)にフォーカスがあるかどうかを検出する方法が必要です。iframeからのメッセージの送信やタブフォーカスイベントの通知の取得
私はこれ試してみた:
window.addEventListener("focus",function(){
console.log("Focus event fired")
});
をしかし、ユーザーがページのどこかをクリックした後にイベントにのみ発生します。ユーザーがタブのヘッダーをクリックしてそのタブにフォーカスを置くたびに呼び出される必要があります。いくつかの調査の後で、私はvisibilitychange
イベントを見つけました。それは私が必要としたことをしましたが、HTML5ページだけでした。だから私は、私はちょうど動的にイベントリスナを含む(<!DOCTYPE html>
宣言付き)のiframeを作成し、Webページに注入でき考え出し:
var iframeId = "pmIframeId";
var iframe = document.createElement("iframe");
iframe.id = iframeId;
document.body.appendChild(iframe);
// Set up the iframe structure and declare it HTML5
var idocument = iframe.contentDocument;
idocument.open();
idocument.write("<!DOCTYPE html>");
idocument.write("<html>");
idocument.write("<head></head>");
idocument.write("<body>");
// Write the event listener code to the iframe
var source = chrome.extension.getURL("pmIframe.js");
idocument.write("<script src='"+source+"'></script>");
idocument.write("</body>");
idocument.write("</html>");
idocument.close();
pmIframe.js
のソースコードは次のとおりです。
function setup(){
console.log("iframe dom loaded") // This does indeed write to the console
document.addEventListener('visibilitychange', function(){
var obj = {};
obj.action = 'visibilitychange';
// The following two lines are hardcoded just for testing
// but refer to a real extension id and an active tab
var extId = 'jbkncfmkbfgbfcjhchonlpbgajopfbgc';
var tabId = '17';
// The following two lines appear to execute (no errors), but my
// background nor content pages ever get the message
chrome.runtime.sendMessage(tabId, obj, function(){});
chrome.runtime.sendMessage(extId, obj, function(){});
});
}
window.addEventListener('DOMContentLoaded', setup);
私は」 manifest.jsonにexternally_connectable
キーが含まれていないため、メッセージが送信されていないことを確認できます。しかし、たとえそれが指定されていても、指定された値は少なくとも2番目のレベルのドメインでなければなりません。「*」は許されません。これはすべてのページで動作する必要があります。
私の質問は、作成したインラインフレームからメッセージを送信してWebページに挿入できますか?タブフォーカスイベントを検出するより良い方法はありますか?
それでした!ありがとうございました。 –