使用 JavaScript 的插播式廣告範例程式碼

警告

自 2020 年 6 月 1 日起,Windows UWP 應用程式的 Microsoft 廣告收益平台將會關閉。 深入了解

本主題提供顯示插播式廣告的基本 JavaScript 和 HTML 通用 Windows 平台 (UWP) 應用程式的完整範例程式碼。 如需示範如何設定專案以使用此程式碼的逐步指示,請參閱插播式廣告。 如需完整的範例專案,請參閱 GitHub 上的廣告範例

程式碼範例

本節說明在顯示插播式廣告的基本應用程式中 HTML 和 JavaScript 檔案的內容。 若要使用這些範例,請將此程式碼複製到 Visual Studio 中的 JavaScript WinJS 應用程式 (通用 Windows) 專案。

此範例應用程式會使用兩個按鈕來要求,然後推出插播式廣告。 Visual Studio 所產生的 main.js 和 index.html 檔案已經過修改,如下所示。 下列 script.js 檔案包含範例中大部分的程式碼,您應該將此檔案新增至專案中的 js 資料夾。

將應用程式提交至市集之前,將 applicationIdadUnitId 變數的值取代為合作夥伴中心的即時值。 如需詳細資訊,請參閱在您的應用程式中設定廣告單元

注意

若要更改此範例以顯示插播式橫幅,而不是插播式影片廣告,請將 InterstitialAdType.display 值傳遞至 RequestAd 方法的第一個參數,而不是 InterstitialAdType.video。 如需詳細資訊,請參閱插播式廣告

index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>InterstitialAdSamplesJS</title>
    <link href="lib/winjs-4.0.1/css/ui-light.css" rel="stylesheet" />
    <script src="lib/winjs-4.0.1/js/base.js"></script>
    <script src="lib/winjs-4.0.1/js/ui.js"></script>
    <link href="css/default.css" rel="stylesheet" />
    <!-- JavaScript files containing code for this example -->
    <script src="js/main.js"></script>
    <script src="js/script.js"></script>
    <!-- Required reference for InterstitialAd -->
    <script src="//Microsoft.Advertising.JavaScript/ad.js"></script>
</head>
<body class="win-type-body">
    <button id="requestAdButton" onclick="requestAdButtonClick" class="win-button">Request ad</button>
    <button id="showAdButton" onclick="showAdButtonClick" class="win-button">Show ad</button>
    <div id="description" style="height:100%; overflow:auto"></div>
</body>
</html>

script.js

(function () {
    "use strict";

    // Assign applicationId and adUnitId to test values. Replace these values with live values 
    // from Dev Center before you submit your app to the Store.
    var interstitialAd = null;
    var applicationId = "d25517cb-12d4-4699-8bdc-52040c712cab";
    var adUnitId = "test";

    window.startInterstitial = function () {
        writeText("<br>Interstitial ads in JavaScript UWP apps");
        registerButtonEvents();

        // Initialize the InterstitialAd object and set up event handlers for it.
        prepareInterstitial();

        writeText("Press the buttons to request and show an interstitial ad.");
    };

    var registerButtonEvents = function () {
        requestAdButton.addEventListener("click", requestAdButtonClick);
        showAdButton.addEventListener("click", showAdButtonClick);
    };

    // This example requests an interstitial ad when the "Request ad" button is clicked. In a real app, 
    // you should request the interstitial ad close to when you think it will be shown, but with 
    // enough advance time to make the request and prepare the ad (say 30 seconds to a few minutes).
    // To show an interstitial banner ad instead of an interstitial video ad, replace InterstitialAdType.video 
    // with InterstitialAdType.display.
    var requestAdButtonClick = function (evt) {
        if (interstitialAd) {
            interstitialAd.requestAd(MicrosoftNSJS.Advertising.InterstitialAdType.video, applicationId, adUnitId);
        }
    }

    // This example attempts to show the interstitial ad when the "Show ad" button is clicked.
    var showAdButtonClick = function (evt) {
        if (interstitialAd && interstitialAd.state !== MicrosoftNSJS.Advertising.InterstitialAdState.showing) {
            showInterstitial();
        }
    }

    var restart = function () {
        if (interstitialAd) {
            interstitialAd.dispose();
        }
        interstitialAd = null;
        window.startInterstitial();
    };

    var clearText = function (msg) {
        description.innerHTML = "";
    };

    var writeText = function (msg) {
        description.innerHTML = description.innerHTML + msg + "<br>";
        description.scrollTop = description.scrollHeight;
    };

    var prepareInterstitial = function () {
        if (!interstitialAd) {
            interstitialAd = new MicrosoftNSJS.Advertising.InterstitialAd();
            interstitialAd.onErrorOccurred = errorOccurredHandler;
            interstitialAd.onAdReady = adReadyHandler;
            interstitialAd.onCancelled = cancelledHandler;
            interstitialAd.onCompleted = completedHandler;
        }
    };

    var showInterstitial = function () {
        if (interstitialAd && interstitialAd.state === MicrosoftNSJS.Advertising.InterstitialAdState.ready) {
            interstitialAd.show();
        } else {
            // No ad is available to show. Allow user to try again anyway
            clearText();
            writeText("<br>Unable to show an ad. Check the error log. You can try again.");
            restart();
        }
    };

    var errorOccurredHandler = function (sender, args) {
        console.log("error: " + args.errorMessage + " (" + args.errorCode + ")");
        if (!isPlaying) {
            clearText();
            writeText("<br>Unable to show an ad. Check the error log. You can try again.");
            restart();
        }
    };

    var adReadyHandler = function (sender) {
        console.log("Ad ready");
    };

    var cancelledHandler = function (sender) {
        console.log("Ad cancelled");
        writeText("<br>You must watch the entire ad to continue. <b>Press the button to watch the ad.</b>");
        interstitialAd.dispose();
        interstitialAd = null;
        prepareInterstitial();
    };

    var completedHandler = function (sender) {
        console.log("Ad complete");
        clearText();
        writeText("<br>Thanks for watching the ad! You can try again!");
        restart();
    };

})();

main.js

(function () {
    "use strict";

    var app = WinJS.Application;
    var activation = Windows.ApplicationModel.Activation;
    var isFirstActivation = true;

    app.onactivated = function (args) {
        if (args.detail.kind === activation.ActivationKind.voiceCommand) {
            // TODO: Handle relevant ActivationKinds. For example, if your app can be started by voice commands,
            // this is a good place to decide whether to populate an input field or choose a different initial view.
        }
        else if (args.detail.kind === activation.ActivationKind.launch) {
            // A Launch activation happens when the user launches your app via the tile
            // or invokes a toast notification by clicking or tapping on the body.
            if (args.detail.arguments) {
                // TODO: If the app supports toasts, use this value from the toast payload to determine where in the app
                // to take the user in response to them invoking a toast notification.
            }
            else if (args.detail.previousExecutionState === activation.ApplicationExecutionState.terminated) {
                // TODO: This application had been suspended and was then terminated to reclaim memory.
                // To create a smooth user experience, restore application state here so that it looks like the app never stopped running.
                // Note: You may want to record the time when the app was last suspended and only restore state if they've returned after a short period.
            }
        }

        if (!args.detail.prelaunchActivated) {
            // TODO: If prelaunchActivated were true, it would mean the app was prelaunched in the background as an optimization.
            // In that case it would be suspended shortly thereafter.
            // Any long-running operations (like expensive network or disk I/O) or changes to user state which occur at launch
            // should be done here (to avoid doing them in the prelaunch case).
            // Alternatively, this work can be done in a resume or visibilitychanged handler.
        }

        if (isFirstActivation) {
            // TODO: The app was activated and had not been running. Do general startup initialization here.
            document.addEventListener("visibilitychange", onVisibilityChanged);

            // Initialize interstitial ad support. 
            startInterstitial();

            args.setPromise(WinJS.UI.processAll());
        }

        isFirstActivation = false;
    };

    function onVisibilityChanged(args) {
        if (!document.hidden) {
            // TODO: The app just became visible. This may be a good time to refresh the view.
        }
    }

    app.oncheckpoint = function (args) {
        // TODO: This application is about to be suspended. Save any state that needs to persist across suspensions here.
        // You might use the WinJS.Application.sessionState object, which is automatically saved and restored across suspension.
        // If you need to complete an asynchronous operation before your application is suspended, call args.setPromise().
    };

    app.start();

})();