diff options
Diffstat (limited to 'files/zh-tw/code_snippets')
-rw-r--r-- | files/zh-tw/code_snippets/index.html | 190 | ||||
-rw-r--r-- | files/zh-tw/code_snippets/tabbed_browser/index.html | 398 |
2 files changed, 588 insertions, 0 deletions
diff --git a/files/zh-tw/code_snippets/index.html b/files/zh-tw/code_snippets/index.html new file mode 100644 index 0000000000..095e91dae2 --- /dev/null +++ b/files/zh-tw/code_snippets/index.html @@ -0,0 +1,190 @@ +--- +title: Code snippets +slug: Code_snippets +tags: + - Add-ons + - Code snippets + - Extensions + - NeedsTranslation + - TopicStub +translation_of: Archive/Add-ons/Code_snippets +--- +<p>This is a quick list of useful code snippets (small code samples) available for developers of extensions for the various Mozilla applications. Many of these samples can also be used in XULRunner applications, as well as in actual Mozilla code itself.</p> +<p>These examples demonstrate how to accomplish basic tasks that might not be immediately obvious.</p> +<h2 id="General" name="General">General</h2> +<dl> + <dt> + <a href="/en-US/docs/Code_snippets/From_articles" title="/en-US/docs/Code_snippets/From_articles">Examples and demos from MDN articles</a></dt> + <dd> + A collection of examples and demos from articles.</dd> + <dt> + <a href="/en-US/docs/Code_snippets/Windows" title="/en-US/docs/Code_snippets/Windows">Windows code</a></dt> + <dd> + Opening and manipulating windows</dd> + <dt> + <a href="/en-US/docs/Code_snippets/Toolbar" title="/en-US/docs/Code_snippets/Toolbar">Toolbar</a></dt> + <dd> + Toolbar related code</dd> + <dt> + <a href="/en-US/docs/Code_snippets/Sidebar" title="/en-US/docs/Code_snippets/Sidebar">Sidebar</a></dt> + <dd> + Sidebar related code</dd> + <dt> + <a href="/en-US/docs/Code_snippets/XML" title="/en-US/docs/Code_snippets/XML">XML</a></dt> + <dd> + Code used to parse, write, manipulate, etc. XML</dd> + <dt> + <a href="/en-US/docs/Code_snippets/File_I_O" title="/en-US/docs/Code_snippets/File_I/O">File I/O</a></dt> + <dd> + Code used to read, write and process files</dd> + <dt> + <a href="/en-US/docs/Code_snippets/Drag_&_Drop" title="/en-US/docs/Code_snippets/Drag_&_Drop">Drag & Drop</a></dt> + <dd> + Code used to setup and handle drag and drop events</dd> + <dt> + <a href="/en-US/docs/Code_snippets/Dialogs_and_Prompts" title="/en-US/docs/Code_snippets/Dialogs_and_Prompts">Dialogs</a></dt> + <dd> + Code used to display and process dialog boxes</dd> + <dt> + <a href="/en-US/docs/Code_snippets/Alerts_and_Notifications" title="/en-US/docs/Code snippets/Alerts and Notifications">Alerts and Notifications </a></dt> + <dd> + Modal and non-modal ways to notify users</dd> + <dt> + <a href="/en-US/docs/Code_snippets/Preferences" title="/en-US/docs/Code_snippets/Preferences">Preferences</a></dt> + <dd> + Code used to read, write, and modify preferences</dd> + <dt> + <a href="/en-US/docs/Code_snippets/JS_XPCOM" title="/en-US/docs/Code_snippets/JS_XPCOM">JS XPCOM</a></dt> + <dd> + Code used to define and call XPCOM components in JavaScript</dd> + <dt> + <a href="/en-US/docs/Code_snippets/Running_applications" title="/en-US/docs/Code_snippets/Running_applications">Running applications</a></dt> + <dd> + Code used to run other applications</dd> + <dt> + <a href="/en-US/docs/Code_snippets/Canvas" title="/en-US/docs/Code_snippets/Canvas"><code><canvas></code> related</a></dt> + <dd> + <a href="/en-US/docs/HTML/Canvas" title="/en-US/docs/HTML/Canvas">WHAT WG Canvas</a>-related code</dd> + <dt> + <a href="/en-US/docs/Signing_a_XPI" title="/en-US/docs/Signing_a_XPI">Signing a XPI</a></dt> + <dd> + How to sign an XPI with PKI</dd> + <dt> + <a href="/en-US/docs/Code_snippets/Threads" title="/en-US/docs/Code_snippets/Threads">Threads</a></dt> + <dd> + Performing background operations and delaying execution while background operations complete</dd> + <dt> + <a href="/en-US/docs/Code_snippets/Miscellaneous" title="/en-US/docs/Code_snippets/Miscellaneous">Miscellaneous</a></dt> + <dd> + Miscellaneous useful code fragments</dd> + <dt> + <a href="/en-US/docs/Code_snippets/HTML_to_DOM" title="/en-US/docs/Code_snippets/HTML_to_DOM">HTML to DOM</a></dt> + <dd> + Using a hidden browser element to parse HTML to a window's DOM</dd> +</dl> +<h2 id="Browser-oriented_code" name="Browser-oriented_code">JavaScript libraries</h2> +<p>Here are some JavaScript libraries that may come in handy.</p> +<dl> + <dt> + <a href="/en-US/docs/Code_snippets/StringView" title="/en-US/docs/Code_snippets/StringView">StringView</a></dt> + <dd> + A library that implements a <code>StringView</code> view for <a href="/en-US/docs/Web/JavaScript/Typed_arrays" title="/en-US/docs/Web/JavaScript/Typed_arrays">JavaScript typed arrays</a>. This lets you access data in typed arrays using C-like string functions.</dd> +</dl> +<h2 id="Browser-oriented_code" name="Browser-oriented_code">Browser-oriented code</h2> +<dl> + <dt> + <a href="/en-US/docs/Code_snippets/Tabbed_browser" title="/en-US/docs/Code_snippets/Tabbed_browser">Tabbed browser code</a> (Firefox/SeaMonkey)</dt> + <dd> + Basic operations, such as page loading, with the tabbed browser, which is the heart of Mozilla's browser applications</dd> + <dt> + <a href="/en-US/docs/Code_snippets/Cookies" title="/en-US/docs/Code_snippets/Cookies">Cookies</a></dt> + <dd> + Reading, writing, modifying, and removing cookies</dd> + <dt> + <a href="/en-US/docs/Code_snippets/Page_Loading" title="/en-US/docs/Code_snippets/Page_Loading">Page Loading</a></dt> + <dd> + Code used to load pages, reload pages, and listen for page loads</dd> + <dt> + <a href="/en-US/docs/Code_snippets/Interaction_between_privileged_and_non-privileged_pages" title="/en-US/docs/Code_snippets/Interaction_between_privileged_and_non-privileged_pages">Interaction between privileged and non-privileged code</a></dt> + <dd> + How to communicate from extensions to websites and vice-versa.</dd> + <dt> + <a href="/en-US/docs/Code_snippets/Downloading_Files" title="/en-US/docs/Code_snippets/Downloading_Files">Downloading Files</a></dt> + <dd> + Code to download files, images, and to monitor download progress</dd> + <dt> + <a href="/en-US/docs/Code_snippets/Password_Manager" title="/en-US/docs/Code_snippets/Password_Manager">Password Manager</a></dt> + <dd> + Code used to read and write passwords to/from the integrated password manager</dd> + <dt> + <a href="/en-US/docs/Code_snippets/Bookmarks" title="/en-US/docs/Code_snippets/Bookmarks">Bookmarks</a></dt> + <dd> + Code used to read and write bookmarks</dd> + <dt> + <a href="/en-US/docs/Code_snippets/JavaScript_Debugger_Service" title="/en-US/docs/Code_snippets/JavaScript_Debugger_Service">JavaScript Debugger Service</a></dt> + <dd> + Code used to interact with the JavaScript Debugger Service</dd> +</dl> +<h2 id="SVG" name="SVG">SVG</h2> +<dl> + <dt> + <a href="/en-US/docs/Code_snippets/SVG_General" title="/en-US/docs/Code_snippets/SVG_General">General</a></dt> + <dd> + General information and utilities</dd> + <dt> + <a href="/en-US/docs/Code_snippets/SVG_Animation" title="/en-US/docs/Code_snippets/SVG_Animation">SVG Animation</a></dt> + <dd> + Animate SVG using JavaScript and SMIL</dd> + <dt> + <a href="/en-US/docs/Code_snippets/SVG_Interacting_with_script" title="/en-US/docs/Code_snippets/SVG_Interacting_with_script">SVG Interacting with Script</a></dt> + <dd> + Using JavaScript and DOM events to create interactive SVG</dd> + <dt> + <a href="/en-US/docs/Code_snippets/Embedding_SVG" title="/en-US/docs/Code_snippets/Embedding_SVG">Embedding SVG in HTML and XUL</a></dt> + <dd> + Using SVG to enhance HTML or XUL based markup</dd> +</dl> +<h2 id="XUL_Widgets" name="XUL_Widgets">XUL Widgets</h2> +<dl> + <dt> + <a href="/en-US/docs/Code_snippets/HTML_in_XUL_for_rich_tooltips" title="/en-US/docs/Code_snippets/HTML_in_XUL_for_rich_tooltips">HTML in XUL for Rich Tooltips</a></dt> + <dd> + Dynamically embed HTML into a XUL element to attain markup in a tooltip</dd> + <dt> + <a href="/en-US/docs/Code_snippets/Label_and_description" title="/en-US/docs/Code_snippets/Label_and_description">Label and description</a></dt> + <dd> + Special uses and line breaking examples</dd> + <dt> + <a href="/en-US/docs/Code_snippets/Tree" title="/en-US/docs/Code_snippets/Tree">Tree</a></dt> + <dd> + Setup and manipulation of trees using XUL and JS</dd> + <dt> + <a href="/en-US/docs/Code_snippets/Scrollbar" title="/en-US/docs/Code_snippets/Scrollbar">Scrollbar</a></dt> + <dd> + Changing style of scrollbars. Applies to scrollbars in browser and iframe as well.</dd> + <dt> + <a href="/en-US/docs/Code_snippets/Autocomplete" title="/en-US/docs/Code_snippets/Autocomplete">Autocomplete</a></dt> + <dd> + Code used to enable form autocomplete in a browser</dd> + <dt> + <a href="/en-US/docs/Code_snippets/Boxes" title="/en-US/docs/Code_snippets/Boxes">Boxes</a></dt> + <dd> + Tips and tricks when using boxes as containers</dd> + <dt> + <a class="internal" href="/en-US/docs/Code_snippets/Tabbox" title="/en-US/docs/Code snippets/Tabbox">Tabbox</a></dt> + <dd> + Removing and manipulating tabs in a tabbox</dd> +</dl> +<h2 id="Windows-specific" name="Windows-specific">Windows-specific</h2> +<dl> + <dt> + <a href="/en-US/docs/Code_snippets/Finding_Window_Handles" title="/en-US/docs/Code_snippets/Finding_Window_Handles">Finding Window Handles (HWND)</a> (Firefox)</dt> + <dd> + How to use Windows API calls to find various kinds of Mozilla window handles. Window handles can be used for IPC and Accessibility purposes.</dd> + <dt> + <a href="/en-US/docs/Accessing_the_Windows_Registry_Using_XPCOM" title="/en-US/docs/Accessing_the_Windows_Registry_Using_XPCOM">Using the Windows Registry with XPCOM</a></dt> + <dd> + How to read, write, modify, delete, enumerate, and watch registry keys and values.</dd> +</dl> +<h2 id="External_links" name="External_links">External links</h2> +<p>The content at <a class="external" href="http://kb.mozillazine.org/Category:Example_code">MozillaZine Example Code</a> is slowly being moved here, but you can still find useful examples there for now.</p> diff --git a/files/zh-tw/code_snippets/tabbed_browser/index.html b/files/zh-tw/code_snippets/tabbed_browser/index.html new file mode 100644 index 0000000000..b8a3b14fff --- /dev/null +++ b/files/zh-tw/code_snippets/tabbed_browser/index.html @@ -0,0 +1,398 @@ +--- +title: Tabbed browser +slug: Code_snippets/Tabbed_browser +translation_of: Archive/Add-ons/Tabbed_browser +--- +<p>您將在此尋獲協助您運用Firefox的多頁籤瀏覽器的一些程式碼片段,註解將提示您應該在什麼地方插入您自己的程式碼。</p> +<p> </p> +<p>一般來說這些片段會包含其初始化的程式碼。基本假設是這些程式碼片段將於瀏覽器視窗內容中執行,最佳做法是以<a href="/en/Extension_Frequently_Asked_Questions#Why_doesn.27t_my_script_run_properly.3F" title="en/Extension_Frequently_Asked_Questions#Why_doesn.27t_my_script_run_properly.3F"> load listener </a>來運行。若您要從瀏覽器視窗以外的地方來操作頁籤,您必須先取得任意一個瀏覽器視窗,詳見: <a href="/en/Working_with_windows_in_chrome_code" title="en/Working_with_windows_in_chrome_code">Working with windows in chrome code</a> 。</p> +<h3 id="Getting_access_to_the_browser" name="Getting_access_to_the_browser">多世界詮釋算什麼,多 browser 詮釋才夠暈</h3> +<p>"browser" 有很多意思。把整個 Firefox 稱為 browser 再為理所當然不過,但是 Firefox 有頁籤,每個頁籤本身也都是 browser。無論是一般所指的 web page browser,還是 XUL 裡的 {{ XULElem("browser") }} element,通通叫做 browser。在本文件和其它某些 Firefox 文件裡, browser 還有另一個意思,就是 Firefox XUL window 裡的 <a href="/en-US/docs/XUL/tabbrowser" title="/en-US/docs/XUL/tabbrowser">tabbrowser</a> element。</p> +<h3 id="Getting_access_to_the_browser" name="Getting_access_to_the_browser">如何存取 browser</h3> +<h4 id="從主視窗">從主視窗</h4> +<p>從 global ChromeWindow 中運行的程式碼,例如套疊 (overlay) 於 <code>browser.xul 的 </code>extension,可以用全域變數 <code>gBrowser 來存取</code> {{ XULElem("tabbrowser") }} element <code>。</code></p> +<pre class="eval">// gBrowser 只存在於 browser window (browser.xul) +gBrowser.addTab(...); +</pre> +<p>如果 <code>gBrowser</code> 未定義,代表您的程式碼要不是太早運行,就是並非從 browser window 中運行。在 browser window 還沒完全載入之前 <code>gBrowser</code> 根本還不存在。若要在視窗一打開時存取 <code>gBrowser</code> ,請在 event listener 中使用它,並 <a href="/en/DOM/element.addEventListener" title="en/DOM/element.addEventListener">listen</a> '<code>load'</code> 事件。</p> +<p>若您的程式是 sidebar 或 dialog 而無法存取主視窗,那就要先獲取主視窗才能使用 <code>gBrowser ,詳見:</code> <a href="/en/Working_with_windows_in_chrome_code" title="en/Working_with_windows_in_chrome_code">Working with windows in chrome code</a>.</p> +<h4 id="從腮巴_(sidebar)_存取_browser">從腮巴 (sidebar) 存取 browser</h4> +<p>若您的附加元件基本上是一坨屎 (sidebar) ,那就:</p> +<pre class="brush: js">var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor) + .getInterface(Components.interfaces.nsIWebNavigation) + .QueryInterface(Components.interfaces.nsIDocShellTreeItem) + .rootTreeItem + .QueryInterface(Components.interfaces.nsIInterfaceRequestor) + .getInterface(Components.interfaces.nsIDOMWindow); + +mainWindow.gBrowser.addTab(...); +</pre> +<h4 id="從呆鴨肉_(dialog)_存取_browser">從呆鴨肉 (dialog) 存取 browser</h4> +<p>若您的程式基本上運行於某種呆鴨肉 (dialog) ,而且是從 browser window 直接甩出來的精選優質肥美呆鴨肉,那就:</p> +<pre class="brush: js">window.opener.gBrowser.addTab(...); +</pre> +<p>如果 <code>window.opener</code> 搞不定,那就用以下的程式碼先取得最近打開的 browser window :</p> +<pre class="brush: js">var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"] + .getService(Components.interfaces.nsIWindowMediator); + +var mainWindow = wm.getMostRecentWindow("navigator:browser"); +mainWindow.gBrowser.addTab(...);</pre> +<h3 id="Opening_a_URL_in_a_new_tab" name="Opening_a_URL_in_a_new_tab">如何以 URL 開啟新 tab</h3> +<pre class="brush: js">// Add tab +gBrowser.addTab("http://www.google.com/"); + +// Add tab, then make active +gBrowser.selectedTab = gBrowser.addTab("http://www.google.com/"); +</pre> +<h4 id="Manipulating_content_of_a_new_tab" name="Manipulating_content_of_a_new_tab">操作新頁籤的內容</h4> +<p>若要操作新開啟頁籤的內容,就要等它載入完。</p> +<pre class="brush: js">// 醬子不行啊 .. 人家還沒準備好 +var newTabBrowser = gBrowser.getBrowserForTab(gBrowser.addTab("http://www.google.com/")); +alert(newTabBrowser.contentDocument.body.innerHTML); + +// BETTER WAY +var newTabBrowser = gBrowser.getBrowserForTab(gBrowser.addTab("http://www.google.com/")); +newTabBrowser.addEventListener("load", function () { + newTabBrowser.contentDocument.body.innerHTML = "<div>hello world</div>"; +}, true); +</pre> +<p>onLoad handler 中的 event target 是個 'tab' XUL element。 關於 getBrowserForTab(),參見: <a href="/en/XUL/tabbrowser#m-getBrowserForTab" title="en/XUL/tabbrowser#m-getBrowserForTab">tabbrowser</a> 。</p> +<h4 id="Opening_a_URL_in_the_correct_window.2Ftab" name="Opening_a_URL_in_the_correct_window.2Ftab">如何精準地在 window 或 tab 開啟 URL</h4> +<p><code><a class="external" href="http://mxr.mozilla.org/mozilla-central/source/browser/base/content/utilityOverlay.js" rel="external nofollow" title="http://mxr.mozilla.org/mozilla-central/source/browser/base/content/utilityOverlay.js">chrome://browser/content/utilityOverlay.js</a></code> 中有許多方法例如 <code>openUILinkIn</code> 和 <code>openUILink,</code> 讓 tab 開啟 URL 變簡單。</p> +<dl> + <dt> + <code>openUILinkIn( url, where, allowThirdPartyFixup, postData, referrerUrl ) </code></dt> + <dd> + where 可以是: + <ul> + <li>"current" 目前 tab (要是 browser window 連個鬼都沒的話就開新視窗)</li> + <li>"tab" 新的 tab (一樣,鬼都沒有就開新視窗)</li> + <li>"tabshifted" 也是新 tab,但若預設選定新 tab 則會在背景開啟,若預設相反則行為相反 (這就是為什麼叫 shifted)</li> + <li>"window" 新視窗</li> + <li>"save" 直接存檔 (不會提示檔名喔!)</li> + </ul> + </dd> + <dt> + <code>openUILink( url, e, ignoreButton, ignoreAlt, allowKeywordFixup, postData, referrerUrl ) </code></dt> + <dd> + </dd> +</dl> +<p>下列程式碼將開啟 URL 並依照什麼鬼滑鼠鍵和什麼鬼熱鍵(例:Ctrl)被按下來開新視窗、開新 tab 或是開在現有的 tab 。這是用於 {{ XULElem("menuitem") }} 的程式碼,而在其它的 XUL elements 上也沒什麼兩樣,但只限 browser.xul 的 overlay 。</p> +<p>XUL:</p> +<pre class="eval"><menuitem oncommand="myExtension.foo(event)" onclick="checkForMiddleClick(this, event)" label="Click me"/> +</pre> +<p>JS:</p> +<pre class="brush: js">var myExtension = { + foo: function(event) { + openUILink("http://www.example.com", event, false, true); + } +}</pre> +<h4 id="如何優柔寡斷地開啟_URL">如何優柔寡斷地開啟 URL</h4> +<pre class="brush: js">var gSessionStore = Cc["@mozilla.org/browser/sessionstore;1"].getService(Ci.nsISessionStore); + +// 生一個新 tab 但是沒載入內容 +var url = "https://developer.mozilla.org"; +var tab = gBrowser.addTab(null); +gSessionStore.setTabState(tab, + '{\ + "entries":[\ + {\ + "url":"' + url + '",\ + "title":"' + url + '"\ + }\ + ],\ + "lastAccessed":0,\ + "index":1,\ + "hidden":false,\ + "attributes":{},\ + "image":null\ + }' +); +</pre> +<h4 id="Reusing_tabs" name="Reusing_tabs">tab 再利用</h4> +<p>與其每次需要就再開新的 tab,若已有 tab 開啟了欲前往的 URL,最佳做法就是試著重用它。遵循這個做法可使您的附加元件開啟最少的 tab。</p> +<h5 id="Reusing_by_URL.2FURI" name="Reusing_by_URL.2FURI">依 URL/URI 來重用</h5> +<p>附加元件常見的一項功能是,當 user 按下某個按鈕或連結就從browser window 中將 user 導向至某個 <code>chrome://</code> 開頭的 URI (像是 help 或 about 這種) 或者一個外部的 HTML (on-line <code>http(s)://</code>) 。接下來的程式碼展示如何重用已顯示所欲前往 URL/URI 的頁籤,如果沒有現存的,則會開個新的。</p> +<pre class="brush: js">function openAndReuseOneTabPerURL(url) { + var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"] + .getService(Components.interfaces.nsIWindowMediator); + var browserEnumerator = wm.getEnumerator("navigator:browser"); + + // Check each browser instance for our URL + var found = false; + while (!found && browserEnumerator.hasMoreElements()) { + var browserWin = browserEnumerator.getNext(); + var tabbrowser = browserWin.gBrowser; + + // Check each tab of this browser instance + var numTabs = tabbrowser.browsers.length; + for (var index = 0; index < numTabs; index++) { + var currentBrowser = tabbrowser.getBrowserAtIndex(index); + if (url == currentBrowser.currentURI.spec) { + + // The URL is already opened. Select this tab. + tabbrowser.selectedTab = tabbrowser.tabContainer.childNodes[index]; + + // Focus *this* browser-window + browserWin.focus(); + + found = true; + break; + } + } + } + + // Our URL isn't open. Open it now. + if (!found) { + var recentWindow = wm.getMostRecentWindow("navigator:browser"); + if (recentWindow) { + // Use an existing browser window + recentWindow.delayedOpenTab(url, null, null, null, null); + } + else { + // No browser windows are open, so open a new one. + window.open(url); + } + } +} +</pre> +<h5 id="Reusing_by_other_criteria" name="Reusing_by_other_criteria">依其它準則來重用</h5> +<p>有時候您可能想重用某個先前已由您的附加元件開啟的頁籤,管它目前 URL/URI 是什麼,只要不是其他的元件開啟的。您的確可以為所欲為,只要在第一次開啟時給它一個自訂屬性。之後要重用它的時候,就從所有已開啟的頁籤找出這個有自訂屬性的頁籤,變更其 URL/URI 並 focus 或 select 該頁籤。要是連個屁都沒有 (可能被 user 關了或是根本沒開過),那就開個新的然後給它這個自訂屬性。</p> +<pre class="brush: js">function openAndReuseOneTabPerAttribute(attrName, url) { + var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"] + .getService(Components.interfaces.nsIWindowMediator); + for (var found = false, index = 0, tabbrowser = wm.getEnumerator('navigator:browser').getNext().gBrowser; + index < tabbrowser.tabContainer.childNodes.length && !found; + index++) { + + // Get the next tab + var currentTab = tabbrowser.tabContainer.childNodes[index]; + + // Does this tab contain our custom attribute? + if (currentTab.hasAttribute(attrName)) { + + // Yes--select and focus it. + tabbrowser.selectedTab = currentTab; + + // Focus *this* browser window in case another one is currently focused + tabbrowser.ownerDocument.defaultView.focus(); + found = true; + } + } + + if (!found) { + // Our tab isn't open. Open it now. + var browserEnumerator = wm.getEnumerator("navigator:browser"); + var tabbrowser = browserEnumerator.getNext().gBrowser; + + // Create tab + var newTab = tabbrowser.addTab(url); + newTab.setAttribute(attrName, "xyz"); + + // Focus tab + tabbrowser.selectedTab = newTab; + + // Focus *this* browser window in case another one is currently focused + tabbrowser.ownerDocument.defaultView.focus(); + } +} +</pre> +<p>該函式應如此這般調用:</p> +<pre class="eval"><span class="nowiki">openAndReuseOneTabPerAttribute("myextension-myattribute", "http://developer.mozilla.org/")</span>. +</pre> +<h3 id="Closing_a_tab" name="Closing_a_tab">如何砍掉 tab</h3> +<p>下列程式碼將砍掉目前選擇的 tab。</p> +<pre class="eval">gBrowser.removeCurrentTab(); +</pre> +<p>另有一個更廣用的 <code>removeTab</code> 方法,以 XUL {{ XULElem("tab") }} element 為唯一的參數。</p> +<h3 id="Changing_active_tab" name="Changing_active_tab">如何改變 active tab</h3> +<p>左三圈 .. ok,並沒有三圈 .. 選定向左一個 tab:</p> +<pre>gBrowser.tabContainer.advanceSelectedTab(-1, true); +</pre> +<p>右三圈 (喔 .. 抱歉)</p> +<pre>gBrowser.tabContainer.advanceSelectedTab(1, true); +</pre> +<h3 id="Changing_active_tab" name="Changing_active_tab">如何偵測 page load</h3> +<p>另見: <a href="/en/Code_snippets/On_page_load" title="en/Code_snippets/On_page_load">Code snippets:On page load</a></p> +<pre class="brush: js">function examplePageLoad(event) { + if (event.originalTarget instanceof HTMLDocument) { + var win = event.originalTarget.defaultView; + if (win.frameElement) { + // Frame within a tab was loaded. win should be the top window of + // the frameset. If you don't want do anything when frames/iframes + // are loaded in this web page, uncomment the following line: + // return; + // Find the root document: + win = win.top; + } + } +} + +// do not try to add a callback until the browser window has +// been initialised. We add a callback to the tabbed browser +// when the browser's window gets loaded. +window.addEventListener("load", function () { + // Add a callback to be run every time a document loads. + // note that this includes frames/iframes within the document + gBrowser.addEventListener("load", examplePageLoad, true); +}, false); + +... +// When no longer needed +gBrowser.removeEventListener("load", examplePageLoad, true); +... +</pre> +<h3 id="Notification_when_a_tab_is_added_or_removed" name="Notification_when_a_tab_is_added_or_removed">tab 增減通知</h3> +<pre class="brush: js">function exampleTabAdded(event) { + var browser = gBrowser.getBrowserForTab(event.target); + // browser is the XUL element of the browser that's been added +} + +function exampleTabMoved(event) { + var browser = gBrowser.getBrowserForTab(event.target); + // browser is the XUL element of the browser that's been moved +} + +function exampleTabRemoved(event) { + var browser = gBrowser.getBrowserForTab(event.target); + // browser is the XUL element of the browser that's been removed +} + +// During initialization +var container = gBrowser.tabContainer; +container.addEventListener("TabOpen", exampleTabAdded, false); +container.addEventListener("TabMove", exampleTabMoved, false); +container.addEventListener("TabClose", exampleTabRemoved, false); + +// When no longer needed +container.removeEventListener("TabOpen", exampleTabAdded, false); +container.removeEventListener("TabMove", exampleTabMoved, false); +container.removeEventListener("TabClose", exampleTabRemoved, false); +</pre> +<div class="geckoVersionNote"> + <p>{{ gecko_callout_heading("1.9.1") }}</p> + <p>Starting in Gecko 1.9.1 {{ geckoRelease("1.9.1") }}, there's an easy way to <a href="/En/Listening_to_events_on_all_tabs" title="https://developer.mozilla.org/en/Listening_to_events_on_all_tabs">listen on progress events on all tabs</a>.</p> +</div> +<p>{{ h2_gecko_minversion("Notification when a tab's attributes change", "2.0") }}</p> +<p>自 Gecko 2.0 起,您可以 listen <code>TabAttrModified</code> event 來得知 tab 之 attribute 異動。event listener 可能收到 tab 異動的 attribute 如下:</p> +<ul> + <li>{{ xulattr("label") }}</li> + <li>{{ xulattr("crop") }}</li> + <li>{{ xulattr("busy") }}</li> + <li>{{ xulattr("image") }}</li> + <li>{{ xulattr("selected") }}</li> +</ul> +<pre class="brush: js">function exampleTabAttrModified(event) { + var tab = event.target; + // Now you can check what's changed on the tab +} + +// During initialization +var container = gBrowser.tabContainer; +container.addEventListener("TabAttrModified", exampleTabAttrModified, false); + +// When no longer needed +container.removeEventListener("TabAttrModified", exampleTabAttrModified, false); +</pre> +<p>{{ h2_gecko_minversion("Notification when a tab is pinned or unpinned", "2.0") }}</p> +<p>自 Gecko 2.0 起,tab 可以被 "釘選";也就是說這類 tab 變成一種特殊的 application tabs ("app tabs"),可以被釘在 tab 列的開頭而且只顯示為 favicon。透過 <code>TabPinned</code> 和 <code>TabUnpinned</code> 事件可以得知 tab 被釘了或被拔了。</p> +<pre class="brush: js">function exampleTabPinned(event) { + var browser = gBrowser.getBrowserForTab(event.target); + // browser is the XUL element of the browser that's been pinned +} + +function exampleTabUnpinned(event) { + var browser = gBrowser.getBrowserForTab(event.target); + // browser is the XUL element of the browser that's been pinned +} + +// Initialization + +var container = gBrowser.tabContainer; +container.addEventListener("TabPinned", exampleTabPinned, false); +container.addEventListener("TabUnpinned", exampleTabUnpinned, false); + +// When no longer needed + +container.removeEventListener("TabPinned", exampleTabPinned, false); +container.removeEventListener("TabUnpinned", exampleTabUnpinned, false); +</pre> +<h3 id="Detecting_tab_selection" name="Detecting_tab_selection">如何偵測 tab 選定</h3> +<p>下列程式碼用來得知 browser 中的 tab 被選定:</p> +<pre class="brush: js">function exampleTabSelected(event) { + var browser = gBrowser.selectedBrowser; + // browser is the XUL element of the browser that's just been selected +} + +// During initialisation +var container = gBrowser.tabContainer; +container.addEventListener("TabSelect", exampleTabSelected, false); + +// When no longer needed +container.removeEventListener("TabSelect", exampleTabSelected, false); +</pre> +<h3 id="Getting_document_of_currently_selected_tab" name="Getting_document_of_currently_selected_tab">如何取得已選定 tab 裡的內文(document)</h3> +<p>下列程式碼用來獲取選定 tab 中的內文(document),於 browser window scope 中運作,例如從 browser window 的 overlay 。</p> +<pre class="eval">gBrowser.contentDocument; +</pre> +<p>或</p> +<pre class="eval">content.document +</pre> +<p>若程式碼是從由 browser window 所開啟的 window 或 dialog,可用以下程式碼獲取已選定 tab 裡所顯示的內文:</p> +<pre class="eval">window.opener.content.document +</pre> +<p>若程式從並非自 browser window 所開啟的 window 或 dialog 中運行,則可用 {{ interface("nsIWindowMediator") }} 獲取最近所使用的 browser window 中已選定 tab 裡的內文。</p> +<pre class="brush: js">var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"] + .getService(Components.interfaces.nsIWindowMediator); +var recentWindow = wm.getMostRecentWindow("navigator:browser"); +return recentWindow ? recentWindow.content.document.location : null; +</pre> +<p>另見: <a href="/en/Working_with_windows_in_chrome_code#Content_windows" title="en/Working_with_windows_in_chrome_code#Content_windows">Working with windows in chrome code</a>.</p> +<h3 id="Enumerating_tabs" name="Enumerating_tabs">如何遍歷 browser</h3> +<p>要遍歷 tabbrowser 中所有的 browser,要先取得任意一個 browser 的 window。如果程式碼是從 <code>browser.xul</code> overlay 執行 (譬如 toolbar button 或者 menu <em>click</em> handler),可以用預定義的 <code>window </code>變數。但若是從獨自的 window 執行 (例如 settings/options dialog) 則要用 {{ interface("nsIWindowMediator") }} 來取得任意一個 browser 的window。</p> +<p>有了一個 window 後再用 <code>win.gBrowser </code>取得其 <code><tabbrowser/></code> element,其中 <code>win</code> 就是上個步驟中所得到的 browser window 。 如果程式是從 <code>browser.xul</code> overlay 執行的話,可以不必寫 window.<code>gBrowser </code>直接用 <code>gBrowser</code> 就好。很奇怪沒錯,在所有的 IDE 當中也沒有 <code>gBrowser 這個東西</code>,但是別忘了您是在開發 Firefox 的 extension , 這是它本身的 object model 。</p> +<p>最後一步,利用 <code>gBrowser.browsers.length</code> 得知 browser 的數量,並用 <code>gBrowser.getBrowserAtIndex()</code> 取得 <code><browser/></code> element。範例:</p> +<pre class="brush: js">var num = gBrowser.browsers.length; +for (var i = 0; i < num; i++) { + var b = gBrowser.getBrowserAtIndex(i); + try { + dump(b.currentURI.spec); // dump URLs of all open tabs to console + } catch(e) { + Components.utils.reportError(e); + } +}</pre> +<p>透過 <a href="/en/DOM_Inspector" title="en/DOM_Inspector">DOM Inspector</a> 或參見 {{ source("toolkit/content/widgets/browser.xml","browser.xml") }} 得知對應的 XBL bindings ( 不然參見 {{ XULElem("browser") }} 及 {{ XULElem("tabbrowser") }} 也行),您將可了解 <code><browser/></code> 和 <code><tabbrowser/></code> elements 有哪些方法可用。</p> +<h3 id="如何取得觸發_http-on-modify-request_notification_的_browser">如何取得觸發 http-on-modify-request notification 的 browser</h3> +<p>關於http-on-* notification 請參見 <a href="/en/Observer_Notifications#HTTP_requests" title="en/Observer_Notifications#HTTP_requests">Observer notifications</a> 。</p> +<p>請注意,部份 HTTP requests 與 tab 無關;例如 RSS feed updates、extension manager requests 以及 XPCOM components 所發出的 XHR requests 等。在這些情況中,下列程式碼將返回 null 。</p> +<div class="warning"> + <strong>注意:</strong>該程式碼使用之 <code>getInterface(Components.interfaces.nsIDOMWindow)</code> 應更新為 {{interface("nsILoadContext")}} ,<a href="/en-US/docs/Updating_extensions_for_Firefox_3.5#Getting_a_load_context_from_a_request" title="/en-US/docs/Updating_extensions_for_Firefox_3.5#Getting_a_load_context_from_a_request">參見範例</a>。</div> +<pre class="brush: js">observe: function (subject, topic, data) { + if (topic == "http-on-modify-request") { + subject.QueryInterface(Components.interfaces.nsIHttpChannel); + var url = subject.URI.spec; /* url being requested. you might want this for something else */ + var browser = this.getBrowserFromChannel(subject); + if (browser != null) { + /* do something */ + } + } +}, + +getBrowserFromChannel: function (aChannel) { + try { + var notificationCallbacks = + aChannel.notificationCallbacks ? aChannel.notificationCallbacks : aChannel.loadGroup.notificationCallbacks; + + if (!notificationCallbacks) + return null; + + var domWin = notificationCallbacks.getInterface(Components.interfaces.nsIDOMWindow); + return gBrowser.getBrowserForDocument(domWin.top.document); + } + catch (e) { + dump(e + "\n"); + return null; + } +} +</pre> +<p>{{ languages( { "fr": "fr/Extraits_de_code/Onglets_de_navigation", "ja": "ja/Code_snippets/Tabbed_browser", "pl": "pl/Fragmenty_kodu/Przegl\u0105danie_w_kartach" } ) }}</p> |