DIV CSS 佈局教程網

用 JavaScript 觸發瀏覽器選單命令:打印、檢視原始碼等
編輯:關於JavaScript     

早期可以透過 document.execCommand() 與 window.external 這類介面,把瀏覽器選單裡的常用命令做成頁面上的按鈕。以下是一組按鈕的寫法。

<input type="button" onclick="document.execCommand('open')" value="打開">
<input type="button" onclick="document.execCommand('saveas')" value="保存">
<input type="button" onclick="document.execCommand('print')" value="打印">
<input type="button" onclick="document.execCommand('selectall')" value="全選">
<input type="button" onclick="location.replace('view-source:'+location)" value="源文件">
<input type="button" onclick="window.external.ShowBrowserUI('PrivacySettings',null)" value="安全選項">
<input type="button" onclick="window.external.ShowBrowserUI('LanguageDialog', null)" value="語言設置">
<input type="button" onclick="window.external.AddFavorite(location.href, document.title)" value="加入收藏夾">
<input type="button" onclick="window.external.ShowBrowserUI('OrganizeFavorites', null)" value="整理收藏夾">
<input type="button" value="刷新" name="refresh" onclick="window.location.reload()">
<input type="button" value="導入收藏夾" onclick="window.external.ImportExportFavorites(true,'');">
<input type="button" value="導出收藏夾" onclick="window.external.ImportExportFavorites(false,'');">

現在還能用哪些

這批 API 的相容性差距極大,實測結果大致如下:

· window.print():唯一推薦使用的。所有現代瀏覽器都支援,且比 execCommand('print') 更明確。

· location.reload():完全可用,重新整理頁面。

· execCommand('selectAll'):在仍支援 execCommand 的瀏覽器上可用,但該 API 已被標記為不建議使用。

· execCommand('open') / ('saveas'):出於安全考量早已被移除,瀏覽器不會允許網頁開啟本機檔案或存檔。

· view-source: 協定:現代瀏覽器已禁止從頁面跳轉到檢視原始碼。

· window.external.*:純 IE 專屬,其餘瀏覽器完全沒有這個物件。

所以這份清單在今天只剩「打印」與「刷新」兩個按鈕實際有效。

現代對應做法

<!-- 打印 -->
<button onclick="window.print()">打印本頁</button>

<!-- 全選頁面內容 -->
<button onclick="var r=document.createRange();r.selectNodeContents(document.body);
var s=window.getSelection();s.removeAllRanges();s.addRange(r);">全選</button>

<!-- 複製到剪貼板(需 https 或 localhost) -->
<button onclick="navigator.clipboard.writeText(location.href)">複製連結</button>

若真的需要「存檔」功能,正確做法是在後端產生 PDF 或讓使用者用瀏覽器的「列印 → 儲存成 PDF」,而不是試圖操作瀏覽器選單。至於整理收藏夾、切換語言、匯入匯出書籤這些,屬於使用者個人設定,網頁本來就不該有權限碰觸。

打印的部分若想要更好的版面,建議搭配 @media print 樣式,把不必要的導覽列、側邊欄隱藏起來,輸出結果會專業很多。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved