Sunday, 4 June 2023

How to modify the query context when using a jQuery instance across iframes

For an existing webapp1, i am using a jQuery instance across iframes which causes me headaches.

jQuery is loaded (and aliased to $jq) in a Document which contains an iFrame(for a sidebar). In the iFrame document, I reuse the jQuery from the parent document by creating a new alias in the iFrame like $jq = window.parent.$jq.

The problem is now, that queries made in the iFrame refer to the Parent-Document, i.e. $jq("body").attr("id") yields the id of the body of the parent document not the id of the body of the iframe-document, so I would have to query with the context parameter like $jq("body", document).attr("id") to get the id of the document jQuery is currently being executed in.

My Question is: can I do anything, so I would not have to add the context parameter to every single query in order to scope the queries to the current document? For example, can I set the context globally for jQuery or such?

Parent Document:

<!DOCTYPE html>
<html>
<head>
    <title>Parent</title>
    <style>body{ margin: 0; padding: 0; font-family: sans-serif;} #page{ display: flex; } #main { padding: 10px; flex: 1 0 auto; } #sidebar{ width: 360px; background-color: #fafafa; border: 0; padding: 10px; height: calc(100vh - 20px); } </style>
    <script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
    <script>
        $jq = jQuery;
    </script>
</head>
<body id="Parent">
    <div id="page">
        <iframe id="sidebar" src="sidebar.html"></iframe>
    
        <div id="main">
            <h2>I am the parent</h2>
            <code class="result"></code>
        </main>
    </div>
    
    <script>
        $('.result').html('$jq("body").attr("id"): <b>' + $jq("body").attr("id") + '</b>');
    </script>
</body>
</html>

iFrame Document (sidebar.html):

<!DOCTYPE html>
<html>
<head>
    <title>Sidebar</title>
    <style>body{font-family: sans-serif;}</style>
</head>
<body id="Sidebar">

    <h2>I am the sidebar iFrame</h2>
    <code class="result"></code>
    
    <script>
        var $jq = window.parent.$jq;
        var theId = $jq("body").attr("id");
        var theIdithContext = $jq("body", document).attr("id");
        var el = document.querySelector('code');
        el.innerHTML +=('$jq("body").attr("id"): <b>' + theId + '</b><br><br>');
        el.innerHTML +=('$jq("body", document).attr("id"): <b>' + theIdithContext + '</b>');
        
    </script>
    
</body>
</html>

And here a testcase outlining my problem.


1 which happens to use jQuery and replacing that is out of scope for now



from How to modify the query context when using a jQuery instance across iframes

No comments:

Post a Comment