Navigator: canShare() 方法

可用性有限

此特性不是基線特性,因為它在一些最廣泛使用的瀏覽器中不起作用。

安全上下文: 此功能僅在安全上下文(HTTPS)中可用,且支援此功能的瀏覽器數量有限。

Navigator 介面的 canShare() 方法會在等效呼叫 navigator.share() 會成功時返回 true

當資料無法被驗證時,該方法返回 false。資料可能無效的原因包括:

  • data 引數被省略,或者只包含值未知的屬性。請注意,使用者代理未識別的任何屬性都將被忽略。
  • URL 格式不正確。
  • 指定了檔案,但實現不支援檔案共享。
  • 共享指定資料將被使用者代理視為“惡意共享”。

Web Share APIweb-share 許可權策略的限制。如果支援該許可權但未授予,canShare() 方法將返回 false

語法

js
canShare()
canShare(data)

引數

data 可選

一個定義要測試的共享資料的物件。通常,如果此呼叫返回 true,則會將具有相同屬性的物件傳遞給 navigator.share()

使用者代理未知的屬性將被忽略;共享資料僅根據使用者代理理解的屬性進行評估。所有屬性都是可選的,但必須指定至少一個已知的屬性,否則方法將返回 false

可能的值是

url 可選

一個表示要共享的 URL 的字串。

text 可選

一個表示要共享的文字的字串。

title 可選

一個表示要共享的標題的字串。

files 可選

一個表示要共享的檔案的 File 物件陣列。

返回值

如果指定的資料 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

瀏覽器相容性

另見