我目前正在使自己成为一个站点范围的页面构建器,利用GrapesJS和 JS/jQuery 来获取选定的内容,解析所述内容,最后初始化 GJS。我的问题都源于解析和随后将相对 URL 转换为绝对 URL。
在我的页面上,访问时会发生以下情况:
- 提示我输入网址
- 从 URL 加载文档
- 剥离所有
<script>
s,将它们添加到 GJS 初始化变量(将脚本推src
入 init.canvas.scripts),如果不src
存在,将封闭代码添加到变量中以供稍后注入 <style>
对/<link>
标签重复步骤 3- 将所有链接转换为绝对 URL(使用此解决方案的修改版本)
- 将被操纵的页面放入
<div id="gjs"></div>
init
使用自定义变量初始化 GJS
目前,我使用 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);
}
感恩节快乐!