我如何创建 'temp html' 并加载它?

How can i create 'temp html' and load it?

我现在开发chrome extension。我的程序编辑 web-page(内容脚本),修改后的页面包含很多 hyperlinks.

如果我单击一个 link 并返回,内容脚本将回滚到原始版本。我希望它保持修改状态。

我想,创建temp html file可以解决。首先,我试试这个。

html = '<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>    <title></title></head><body>    <a href ="http://google.com">test html</a></body></html>';

var fileBlob = new Blob([html], {  
    type: 'text/html'
});

var fileUrl = URL.createObjectURL(fileBlob);
location.href = fileUrl;

html只是例子) 上面的代码可以显示修改后的html。但是单击 link 并返回,页面消失了。

接下来,我试试这个。

//at chrome extension
html = '<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>    <title></title></head><body>    <a href ="http://google.com">test html</a></body></html>';

var fileBlob = new Blob([html], {  
    type: 'text/html'
});

var fileUrl = URL.createObjectURL(fileBlob);

var fileName = "temp.html";    

console.log(fileUrl);
var fileOptions = {
    filename: fileName,
    url: fileUrl,
    conflictAction: 'overwrite'  
};

chrome.downloads.download(fileOptions); 

//at content script
window.open('file:///C:/Users/jsl/Downloads/temp.html');

没用。这是错误信息。

Not allowed to load local resource: `file:///C:/Users/jsl/Downloads/temp.html`

我该怎么做?我知道使用服务器可以解决所有问题。但我不想使用服务器。这不可能?

或者,还有其他方法可以在我返回时保持修改后的状态吗?

第三种方法对我很有帮助。

manifast.json

....
"background": {
  "scripts": [ "webpage/bg.js" ],
  "persistent": false
},
....

分机代码:

chrome.tabs.executeScript(null, {
    code: "head = document.head.innerHTML;  body = document.body.innerHTML; source= [head,body]; source"
}, function (data) {
    source = data[0];       
    chrome.runtime.getBackgroundPage(bg => {
        bg.sharedData = JSON.stringify({ source: source });
        chrome.tabs.create({ url: 'webpage/page.html' });
    });
});

page.html :

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
</head>
<body>
    <script src="page.js"></script>
</body>
</html>

page.js

let sharedData = sessionStorage.sharedData;
if (!sharedData) {
    const bg = chrome.extension.getBackgroundPage();
    sharedData = bg && bg.sharedData;
    if (sharedData) {
        sessionStorage.sharedData = sharedData;
    }
}
try {
    sharedData = JSON.parse(sharedData);
    document.head.innerHTML = sharedData.source[0];
    document.body.innerHTML = sharedData.source[1];
} catch (e) { }

bg.js 为空文件。

它非常适合我。使用此代码,我可以刷新页面!点击link后退不回滚页面!