Aksel Gresvig
Aksel Gresvig

Reputation: 765

'deviceorientation' not triggering in iOS browsers when referenced in iFrame

I'm making a website running a "360 panorama viewer" in an iframe, where the source page uses JavaScript and window.DeviceOrientationEvent to determine if user is on a mobile device with orientation functionality. I'm seeing some strange behaviour on iOS Safari & Chrome:

window.DeviceOrientationEvent evaluates to true, but deviceorientation event is never triggered.

This is not the case for Android Chrome - the event is triggered continuously as expected, when used in iFrame.

When accessing the page directly (on iOS) i see the event triggering. It is as if using it in an iframe "blocks" this event somehow.

It makes little sense to me, and researching it reveals little info, except some vague indications[1, 2] that it may actually have to do with the CORS - wether or not the iframe source is on the same root domain as the parent page. This makes even less sense to me..

Anyone have a clue?

1 2

Upvotes: 3

Views: 6644

Answers (3)

Wolfram
Wolfram

Reputation: 8052

This can be solved using Window.postMessage() to pass information to the iframe. You need access to both websites however, the parent and the iframe. First listen to the deviceorientation event in the parent, then pass it into the iframe using postMessage.

// Parent
window.addEventListener("deviceorientation", function (event) {
let iframeElement = document.getElementById("my-iframe");
iframeElement.contentWindow.postMessage({
        alpha: event.alpha,
        beta: event.beta,
        gamma: event.gamma
    },
    "*"
);
// Child
window.addEventListener("message", receiveMessage, false);
function receiveMessage(event) {
    console.debug(event.data);
}

Upvotes: 3

Husky
Husky

Reputation: 6186

For anyone encountering this question now, it seems that Apple has disabled the deviceorientation API since iOS 12.2. Users now need to explicitly toggle it in Settings > Safari > Motion and Orientation access. See here for discussion.

Upvotes: 7

Aksel Gresvig
Aksel Gresvig

Reputation: 765

For anyone curious, I verified the problem to be CORS-related. It must be a security thing Apple does - blocking events on a page when used in iframe

My temp solution is to host files on same server, but its not scalable solution, so I think I'll have to set up some sort of proxy to deal with this.

Upvotes: 2

Related Questions