首页 > 解决方案 > 用 jQuery 的 $.get() 解析 HTML,随后对对象的操作什么都不做

问题描述

我目前正在使自己成为一个站点范围的页面构建器,利用GrapesJS和 JS/jQuery 来获取选定的内容,解析所述内容,最后初始化 GJS。我的问题都源于解析和随后将相对 URL 转换为绝对 URL。

在我的页面上,访问时会发生以下情况:

目前,我使用 jQuery 的$.get()函数加载一个文档,然后使用回调数据(这是一个字符串)进行剥离等。但是,这个字符串无法在没有被解析的情况下用 jQuery 操作,所以我使用parsePage(), 应该理想情况下将此字符串转换为 jQuery 对象。使用“解析”变量,我应该能够.find('img'),不是吗?它什么也没给我...

如果我做错了,如何正确解析页面,同样重要的是,我如何才能将整个文档剥离为仅文档内部的内容<body>


以下是我用来执行此操作的所有 JS:

var nosrc_scripts = "";
var nosrc_styles = "";

var init = {
    container: '#gjs',
    fromElement: true,
    width: 'auto',
    height: 'auto',
    storageManager: false,
    panels: {
        defaults: []
    },
    // load external css/scripts
    // found the reference here: https://github.com/artf/grapesjs/blob/master/src/canvas/config/config.js
    canvas: {
        styles: [],
        scripts: []
    },
};

$(document).ready(function() {
    var url = prompt("URL to load:");
    if (url != null) {
        // get page content in var
        $.get(url, function(page) {
            // fix relative images, scripts, stylesheets, etc.
            page.find('img[src^="./"]').attr('src', function(_,existing){
                return new URL(src, "https://example.com/").href;
            });

            // go through scripts, add tags into the config, and add <script>'s into a var to inject later
            getScripts(page);
            // go through stylesheets, add tags into the config, and add <style>'s into a var to inject later
            getStyles(page);

            // load page content into the div to load
            $('#gjs').append(stripToBody(page));

        });
        // finally, initialize grapesjs with our custom init var
        initializeGJS();
    }
});

function initializeGJS() {
    const editor = grapesjs.init(init);
    // create tags to inject
    var nosrc_scripts_tag = document.createElement('script');
    var nosrc_styles_tag = document.createElement('script');

    // set <script>/<style> tags to the variables to inject
    nosrc_scripts_tag.text = nosrc_scripts;
    nosrc_styles_tag.text = nosrc_styles;
    // inject them into the head of the HTML using grapesjs's method
    editor.Canvas.getDocument().head.appendChild(nosrc_scripts_tag);
    editor.Canvas.getDocument().head.appendChild(nosrc_styles_tag);
}

function getScripts() {
    ...
}

function getStyles() {
    ...
}

function parsePage(page) {
    // strip loaded page down to body HTML, with no <script> or <style> tags
    return $.parseHTML(page.substring(page.indexOf("<body"), page.indexOf("</body>")), false);
}

感恩节快乐!

标签: javascriptjqueryhtmlgetgrapesjs

解决方案


推荐阅读