在Awesomium中加载本地内容

Loading Local Content in Awesomium

本文关键字:加载 Awesomium      更新时间:2023-10-16

我写了一个本地DataSource,因为据我所知,Awesomium中没有包含任何数据源,但问题是它请求数据源html、图像等的所有内容我不知道如何加载所有类型的mime格式。我当前的代码只支持html/text,在这里我将文件加载到二进制文件中并作为响应发送。这对图像不起作用。

有人知道我该从这里走到哪里吗?

class LocalDataSource : 
public Awesomium::DataSource
{
public:
LocalDataSource() { }
virtual ~LocalDataSource() { }
virtual void OnRequest(int request_id, const Awesomium::WebString& path)
{
std::string filepath = Awesomium::ToString(path).insert(0, "./");
std::basic_ifstream<char> is(filepath, std::ios_base::in | std::ios_base::binary);
if (is)
{
is.seekg(0, is.end);
int length = is.tellg();
is.seekg(0, is.beg);
char *buffer = new char[length + 1];
is.read(buffer, length);
buffer[length] = '';
is.close();
SendResponse(request_id, strlen(buffer), (unsigned char*)buffer, Awesomium::WSLit("text/html"));
delete[] buffer;
}
else
{
// Error 
}
}
};

编辑:

现在,我将加载相对于可执行文件的文件,而不使用DataSource。

我知道这是旧的,但它与我有关,我以与Steven相同的方式修复了它,我将发布我使用的C++代码:

bool ResInterceptor::OnFilterNavigation(int origin_process, int origin_routing_id, const Awesomium::WebString& method, const Awesomium::WebURL& url, bool is_main_frame) 
{
return false;
}
Awesomium::ResourceResponse* ResInterceptor::OnRequest(Awesomium::ResourceRequest* request)
{
bool isAsset = std::strcmp(ToString(request->url().scheme()).c_str(), "asset")==0;
bool isFile = std::strcmp(ToString(request->url().scheme()).c_str(), "file")==0;
if(!isAsset && !isFile)
{
//if it is neither of these we "may" still intercept the call, this allows for offline-online versions to work
return Awesomium::ResourceInterceptor::OnRequest(request);
}
if(isAsset)
{
//Blah blah, do whatever
}
else if(isFile)
{
//Blah blah, same
}
//As you can see this isn't very, but it worked for my purposes
std::string contentpath = "E:/Location/of/files" + ToString(request->url().path()); 
Awesomium::WebString datatype;
std::string filename = Awesomium::ToString(request->url().filename());
//I still want to check for the correct mime type
if     (has_suffix(filename, ".html")) datatype = Awesomium::WSLit("text/html");
else if(has_suffix(filename, ".js"))   datatype = Awesomium::WSLit("text/javascript");
else if(has_suffix(filename, ".css"))  datatype = Awesomium::WSLit("text/css");
else if(has_suffix(filename, ".swf"))  datatype = Awesomium::WSLit("application/x-shockwave-flash");
else if(has_suffix(filename, ".zip"))  datatype = Awesomium::WSLit("application/zip");
else if(has_suffix(filename, ".txt"))  datatype = Awesomium::WSLit("text/plain");
else if(has_suffix(filename, ".text")) datatype = Awesomium::WSLit("text/plain");
else if(has_suffix(filename, ".png"))  datatype = Awesomium::WSLit("image/png");
else if(has_suffix(filename, ".jpeg")) datatype = Awesomium::WSLit("image/jpeg");
else if(has_suffix(filename, ".jpg"))  datatype = Awesomium::WSLit("image/jpeg");
else if(has_suffix(filename, ".webm")) datatype = Awesomium::WSLit("video/webm");
else if(has_suffix(filename, ".mp4"))  datatype = Awesomium::WSLit("video/mp4");
else if(has_suffix(filename, ".ogv"))  datatype = Awesomium::WSLit("video/ogg");
else if(has_suffix(filename, ".flv"))  datatype = Awesomium::WSLit("video/flv");
if(!datatype.IsEmpty())
{
FILE * pFile;
long lSize;
unsigned char * buffer;
size_t result;
pFile = fopen ( contentpath.c_str() , "rb" );
if (pFile!=NULL)
{
// obtain file size:
fseek (pFile , 0 , SEEK_END);
lSize = ftell (pFile);
rewind (pFile);
// allocate memory to contain the whole file:
buffer = (unsigned char*) malloc (sizeof(unsigned char)*lSize);
if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}
// copy the file into the buffer:
result = fread (buffer,1,lSize,pFile);
if (result != lSize) {fputs ("Reading error",stderr); exit (3);}
//This is where the magic happens!!
return Awesomium::ResourceResponse::Create(lSize, buffer, datatype);
// terminate
fclose (pFile);
free (buffer);
}
else
{
//send this off to the default request handler instead of it being a local file
return Awesomium::ResourceInterceptor::OnRequest(request);
}
}else
{
//send this off to the default request handler instead of it being a local file
return Awesomium::ResourceInterceptor::OnRequest(request);
}
}
//Support function
bool ResInterceptor::has_suffix(const std::string &str, const std::string &suffix)
{
return str.size() >= suffix.size() &&
str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0;
}

至于我是如何连接的,我只是添加了这行代码:

_web_core = WebCore::Initialize(config);
_web_core->set_resource_interceptor(new ResInterceptor());

这花了我一整晚的时间来确定,因为我传递了一个带有变量的指针,而没有直接使用"new"关键字!至少我现在明白了!

另外请注意,我在LocalDataSource中尝试了与上面完全相同的代码,但除了文本文件外,它对任何东西都不起作用,所以我认为其中有一个错误,好消息是,它的工作方式完全相同,但你可以对每个文件请求进行更多的控制。

感谢史蒂文提供的所有优秀的参考代码!

在不进行mime类型检测的情况下发送文件内容的简单方法是使用静态方法static ResourceResponse* Awesomium::ResourceResponse::Create

来自Awesomium文档:

从磁盘上的文件创建ResourceResponse。

我想不出将ResourceResponse::Create映射到DataSource::SendResponse的方法。

作为一种变通方法,您可以将数据源重写为IResourceInterceptor,而不是DataSource。我在C#中写了一个详细的例子,说明如何使用http://scheme而不是嵌入式资源的自定义asset://scheme将C#转换为C++应该非常简单。以下是我的帖子的编辑版本(未经测试)。

using System;
using System.IO;
using System.Reflection;
using Awesomium.Core;
namespace MyApp
{
public class ResourceInterceptor : IResourceInterceptor
{
/// <summary>
///     Intercepts any requests for the EmbeddedResourceDomain base Uri,
///     and returns a response using the embedded resource in this app's assembly/DLL file
/// </summary>
public virtual ResourceResponse OnRequest(ResourceRequest request)
{
ResourceResponse response = null;
string resourceName;
string filePath;
filePath = String.Concat("./", request.Url.AbsolutePath);
filePath = Path.GetFullPath(resourceName.Replace('/', Path.DirectorySeparatorChar));
// cache the resource to a temp file if 
if (File.Exists(filePath))
{
response = ResourceResponse.Create(filePath);
}
return response;
}
/// <summary>
///     Optionally blocks any web browser requests by returning true.  Not used.
/// </summary>
/// <remarks>
///     This method can implement a whitelist of allowed URLs here by
///     returning true to block any whitelist misses
/// </remarks>
public virtual bool OnFilterNavigation(NavigationRequest request)
{
return false;
}
}
}

另一种选择可能是破解HTML内容,在文档的<head>中注入<base href="file:///c:/my/bin/path" />元素。在加载内容之前,您需要修改href属性值。这可能是超出其价值的工作。