1

Вопросы по срипту логина.

Тема: Вопросы по срипту логина.

При создани скрипта по примеру с возникает ошибка.
Код скрипта что я ввожу:
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Wialon Playground - Login</title>
    <script type="text/javascript" src="https://code.jquery.com/jquery-latest.min.js"></script>
    <script type="text/javascript" src="https://hst-api.wialon.com/wsdk/script/wialon.js"></script>
</head>
<body>
<style>
#log {
  border: 1px solid #c6c6c6;
}
</style>
Token: <input type="text" id="token"/>
<input type="button" value="login" id="login_btn" />
<input type="button" value="logout" id="logout_btn" />
<input type="button" value="get user" id="user_btn" />
<div id="log"></div>
<script type="text/javascript">
// Print message to log
function msg(text) { $("#log").prepend(text + "<br/>"); }
// Login to server using entered username and password
function login() {
    var sess = wialon.core.Session.getInstance(); // get instance of current Session
    var user = sess.getCurrUser(); // get current User
    if( user ) { // if user exists - you are already logged, print username to log
        msg("You are logged as '" + user.getName()+"', click logout button first");
        return;
    }
    // if not logged
    var token = $("#token").val(); // get token from input
    if (!token) { // if token is empty - print message to log
        msg("Enter token");
        return;
    }
    msg("Trying to login with token '"+ token +"'");
    sess.initSession("https://hst-api.wialon.com"); // initialize Wialon session
    sess.loginToken(token, "", // trying login
        function (code) { // login callback
            if (code) msg(wialon.core.Errors.getErrorText(code)); // login failed, print error
            else msg("Logged successfully"); // login succeed
        }
    );
}
// Logout
function logout() {
    var user = wialon.core.Session.getInstance().getCurrUser(); // get current user
    if (!user){ msg("You are not logged, click 'login' button"); return; }
    wialon.core.Session.getInstance().logout( // if user exist - logout
        function (code) { // logout callback
            if (code) msg(wialon.core.Errors.getErrorText(code)); // logout failed, print error
            else msg("Logout successfully"); // logout suceed
        }
    );
}
// Get current user and prints its name to log
function getUser() {
    var user = wialon.core.Session.getInstance().getCurrUser(); // get current user
    // print message
    if (!user) msg("You are not logged, click 'login' button"); // user not exists
    else msg("You are logged as '" + user.getName() + "'"); // print current user name
}
// execute when DOM ready
$(document).ready(function(){
    // For more info about how to generate token check
    // http://sdk.wialon.com/playground/demo/app_auth_token
    $("#token").val("5dce19710a5e26ab8b7b8986cb3c49e58C291791B7F0A7AEB8AFBFCEED7DC03BC48FF5F8");
    // bind actions to buttons click
    $("#login_btn").click( login );
    $("#logout_btn").click( logout );
    $("#user_btn").click( getUser );
});
</script>
</body>
</html>

Вот что выдает файл Host.html к которому мы обращаемся:

<html>
<body>
<script>
(function(){
var isChunkedTransmissionEnabled = false,
    chunkedPrefix = 'posthtml:';
var CHUNK_SIZE;
var chunksQueue = [],
    chunksIntervalId = 0;
function postMessageStr(id, win, str, origin) {
    if (!isChunkedTransmissionEnabled) {
        win.postMessage(str, origin);
        return;
    }
    var offset = 0,
        length = str.length;
    var parts = [];
    // Split `str` by CHUNK_SIZE blocks
    while (offset < length) {
        parts.push(str.slice(offset, offset + CHUNK_SIZE));
        offset += CHUNK_SIZE;
    }
    var chunksCount = parts.length;
    parts.forEach(function(part, i) {
        // Chunk format:
        //     `chunkedPrefix` `id` : `chunkIndex` : `chunksCount` : `data`

        var chunkStr = [chunkedPrefix, id, ':', i, ':', chunksCount, ':', part].join('');
        chunksQueue.push({
            win: win,
            str: chunkStr,
            origin: origin
        });
    });
    // Start chunks processing
    if (!chunksIntervalId) {
        chunksIntervalId = setInterval(processChunksQueue, 0);
    }
}
function processChunksQueue() {
    if (!chunksQueue.length) {
        clearInterval(chunksIntervalId);
        chunksIntervalId = 0;
        return;
    }
    var chunk = chunksQueue.shift();
    chunk.win.postMessage(chunk.str, chunk.origin);
}
/*
* Listen all "postMessage" events
*/
function listener(event) {
    if (!event)
        return;
    var data = null;
    try {
        data = JSON.parse(event.data);
    } catch(e) {
        try {
            // Insecure
            data = eval("(" + event.data + ")");
        } catch (e) {
            return;
        }
    }
    if (!data || data.source != window.location.href)
        return;
    // ping request
    if (!data.id) {
        if (data.chunkedPrefix) {
            chunkedPrefix = data.chunkedPrefix;
        }
        if (data.enableChunkedResult) {
            isChunkedTransmissionEnabled = true;

            CHUNK_SIZE = Math.floor(16777215 - (chunkedPrefix.length * 2) - 64 - 512); // 16mb (32 in UTF16) - (approximate header size) - random
        }
        var responseJson = "{\"id\": 0, \"source\":\"" + data.source + "\", \"error\": 0";
        if (isChunkedTransmissionEnabled) responseJson += ", \"chunkedResult\": true";
        responseJson += "}";

        event.source.postMessage(responseJson, event.origin);
        return;
    }
    // construct request
    var req;
    // creating XMLHttpRequest object for Internet Explorer differs with creating object for other browsers. That's why this operation duplicates for compatibility
    if (window.XMLHttpRequest)
        req = new XMLHttpRequest();                            // normal browser
    else if (window.ActiveXObject)                            // IE
        try {
            req = new ActiveXObject('Msxml2.XMLHTTP');        // different IE versions
        } catch (e) {                                        // create
            try {                                            // object different
                req = new ActiveXObject('Microsoft.XMLHTTP');
            } catch (e) {}
        }
    if (!req) {
        postMessageStr(data.id, event.source, "{\"id\": " + data.id + ", \"source\":\"" + data.source + "\", \"error\": 1}", event.origin);
        return;
    }
    //sending request with POST method and with compulsary pointing to handler file (true - asynchronous mode)
    req.open("POST", data.url, true);
    req.callEventOrigin = event.origin;
    req.callEventSource = event.source;   
    req.callId = data.id;
    req.callUrl = data.url;
    req.source = data.source;
    req.onreadystatechange = function() {
        // status OK
        if (this.readyState == 4) {
            if (this.status != 200 || this.getResponseHeader("Content-Type") != "application/json") {
                postMessageStr(this.callId, this.callEventSource, "{\"id\":" + this.callId + ", \"source\":\"" + this.source + "\", \"error\": 1}", this.callEventOrigin);
                return;
            }
            // getting function response in string
            postMessageStr(this.callId, this.callEventSource, "{\"id\":" + this.callId + ", \"error\": 0, \"source\":\"" + this.source + "\", \"text\": " + this.responseText + "}", this.callEventOrigin);
        }
    };
    // when using XMLHttpRequest object with POST method it is necessary to send additional header
    req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    // sending necessary parameters (several parameters separating with ampersand)
    try {
        req.send(data.params);
    } catch(e) {
        postMessageStr(data.id, event.source, "{\"id\":" + data.id + ", \"source\":\"" + data.source + "\", \"error\": 1}", event.origin);
        return;
    }
}
// bind event
if (window.addEventListener)
    window.addEventListener("message", listener, false);
else
    window.attachEvent("onmessage", listener);
})();
</script>
</body>
</html>

Непосредственно ошибка:

post.html:101 Uncaught DOMException: Failed to execute 'postMessage' on 'Window': Invalid target origin 'null' in a call to 'postMessage'.
    at listener (https://hst-api.wialon.com/wialon/post.html:101:16)

2

Вопросы по срипту логина.

Re: Вопросы по срипту логина.

Скорее всего библиотека не прогрузилась. Запустил в 2х браузерах, все работает. Код правильный.

3

Вопросы по срипту логина.

Re: Вопросы по срипту логина.

Странно. Запускали код с 2 компьютеров с нескольких браузеров и одно и тоже выдает.

4

Вопросы по срипту логина.

Re: Вопросы по срипту логина.

Похоже, что вы открыли файл, сохранённый на компьютере. В этом случае он открывается по как file://. Для работы скрипт должен быть загружен по http.

5

Вопросы по срипту логина.

Re: Вопросы по срипту логина.

Спасибо большое. Помогло. Не попробовал сразу.