Navigator: canShare() 方法
Navigator 介面的 canShare() 方法會在等效呼叫 navigator.share() 會成功時返回 true。
當資料無法被驗證時,該方法返回 false。資料可能無效的原因包括:
data引數被省略,或者只包含值未知的屬性。請注意,使用者代理未識別的任何屬性都將被忽略。- URL 格式不正確。
- 指定了檔案,但實現不支援檔案共享。
- 共享指定資料將被使用者代理視為“惡意共享”。
Web Share API 受 web-share 許可權策略的限制。如果支援該許可權但未授予,canShare() 方法將返回 false。
語法
js
canShare()
canShare(data)
引數
返回值
如果指定的資料 data 可以透過 Navigator.share() 進行共享,則返回 true,否則返回 false。
示例
傳送 MDN URL
該示例使用 navigator.canShare() 來檢查 navigator.share() 是否可以共享指定的資料。
HTML
HTML 僅建立一個段落來顯示測試結果。
html
<p class="result"></p>
JavaScript
js
let shareData = {
title: "MDN",
text: "Learn web development on MDN!",
url: "https://mdn.club.tw",
};
const resultPara = document.querySelector(".result");
if (!navigator.canShare) {
resultPara.textContent = "navigator.canShare() not supported.";
} else if (navigator.canShare(shareData)) {
resultPara.textContent =
"navigator.canShare() supported. We can use navigator.share() to send the data.";
} else {
resultPara.textContent = "Specified data cannot be shared.";
}
結果
下方的框應說明此瀏覽器是否支援 navigator.canShare(),如果支援,我們是否可以使用 navigator.share() 共享指定的資料。
功能檢查示例
此方法進行功能測試,以確定特定資料屬性是否有效且可共享。如果僅使用單個 data 屬性,則僅當該屬性有效且可在平臺上共享時,它才返回 true。
下面的程式碼演示瞭如何驗證資料屬性是否受支援。
js
// Feature that may not be supported
let testShare = { someNewProperty: "Data to share" };
// Complex data that uses new key
const shareData = {
title: "MDN",
text: "Learn web development on MDN!",
url: "https://mdn.club.tw",
someNewProperty: "Data to share",
};
// Test that the key is valid and supported before sharing
if (navigator.canShare(testShare)) {
// Use navigator.share() to share 'shareData'
} else {
// Handle case that new data property can't be shared.
}
規範
| 規範 |
|---|
| Web Share API # canshare-data-method |
瀏覽器相容性
載入中…